/*
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 <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
#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, "setupapi.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
// 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;
volatile BOOL NeedPeriodicDeviceListUpdate = FALSE;
BOOL DisablePeriodicDeviceListUpdate = FALSE;
BOOL EnableMemoryProtection = 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
HMODULE hRichEditDll = NULL;
HMODULE hComctl32Dll = NULL;
HMODULE hSetupDll = NULL;
HMODULE hShlwapiDll = NULL;
HMODULE hProfApiDll = NULL;
HMODULE hUsp10Dll = NULL;
HMODULE hCryptSpDll = NULL;
HMODULE hUXThemeDll = NULL;
HMODULE hUserenvDll = NULL;
HMODULE hRsaenhDll = NULL;
HMODULE himm32dll = NULL;
HMODULE hMSCTFdll = NULL;
HMODULE hfltlibdll = NULL;
HMODULE hframedyndll = NULL;
HMODULE hpsapidll = NULL;
HMODULE hsecur32dll = NULL;
HMODULE hnetapi32dll = NULL;
HMODULE hauthzdll = NULL;
HMODULE hxmllitedll = NULL;
HMODULE hmprdll = NULL;
HMODULE hsppdll = NULL;
HMODULE vssapidll = NULL;
HMODULE hvsstracedll = NULL;
HMODULE hcfgmgr32dll = NULL;
HMODULE hdevobjdll = NULL;
HMODULE hpowrprofdll = NULL;
HMODULE hsspiclidll = NULL;
HMODULE hcryptbasedll = NULL;
HMODULE hdwmapidll = NULL;
HMODULE hmsasn1dll = NULL;
HMODULE hcrypt32dll = NULL;
HMODULE hbcryptdll = NULL;
HMODULE hbcryptprimitivesdll = NULL;
HMODULE hMsls31 = NULL;
HMODULE hntmartadll = NULL;
HMODULE hwinscarddll = NULL;
HMODULE hmsvcrtdll = NULL;
HMODULE hWinTrustLib = NULL;
HMODULE hAdvapi32Dll = NULL;
#define FREE_DLL(h) if (h) { FreeLibrary (h); h = NULL;}
#ifndef BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE
#define BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE 0x00000001
#endif
#ifndef BASE_SEARCH_PATH_PERMANENT
#define BASE_SEARCH_PATH_PERMANENT 0x00008000
#endif
#ifndef LOAD_LIBRARY_SEARCH_SYSTEM32
#define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800
#endif
typedef BOOL (WINAPI *SetDllDirectoryPtr)(LPCWSTR lpPathName);
typedef BOOL (WINAPI *SetSearchPathModePtr)(DWORD Flags);
typedef BOOL (WINAPI *SetDefaultDllDirectoriesPtr)(DWORD DirectoryFlags);
typedef void (WINAPI *InitCommonControlsPtr)(void);
typedef HIMAGELIST (WINAPI *ImageList_CreatePtr)(int cx, int cy, UINT flags, int cInitial, int cGrow);
typedef int (WINAPI *ImageList_AddPtr)(HIMAGELIST himl, HBITMAP hbmImage, HBITMAP hbmMask);
typedef VOID (WINAPI *SetupCloseInfFilePtr)(HINF InfHandle);
typedef HKEY (WINAPI *SetupDiOpenClassRegKeyPtr)(CONST GUID *ClassGuid,REGSAM samDesired);
typedef BOOL (WINAPI *SetupInstallFromInfSectionWPtr)(HWND,HINF,PCWSTR,UINT,HKEY,PCWSTR,UINT,PSP_FILE_CALLBACK_W,PVOID,HDEVINFO,PSP_DEVINFO_DATA);
typedef HINF (WINAPI *SetupOpenInfFileWPtr)(PCWSTR FileName,PCWSTR InfClass,DWORD InfStyle,PUINT ErrorLine);
typedef LSTATUS (STDAPICALLTYPE *SHDeleteKeyWPtr)(HKEY hkey, LPCWSTR pszSubKey);
typedef HRESULT (STDAPICALLTYPE *SHStrDupWPtr)(LPCWSTR psz, LPWSTR *ppwsz);
typedef HRESULT (STDAPICALLTYPE *UrlUnescapeWPtr)(
PWSTR pszUrl,
PWSTR pszUnescaped,
DWORD *pcchUnescaped,
DWORD dwFlags
);
// ChangeWindowMessageFilter
typedef BOOL (WINAPI *ChangeWindowMessageFilterPtr) (UINT, DWORD);
typedef BOOL (WINAPI *CreateProcessWithTokenWFn)(
__in HANDLE hToken,
__in DWORD dwLogonFlags,
__in_opt LPCWSTR lpApplicationName,
__inout_opt LPWSTR lpCommandLine,
__in DWORD dwCreationFlags,
__in_opt LPVOID lpEnvironment,
__in_opt LPCWSTR lpCurrentDirectory,
__in LPSTARTUPINFOW lpStartupInfo,
__out LPPROCESS_INFORMATION lpProcessInformation
);
SetDllDirectoryPtr SetDllDirectoryFn = NULL;
SetSearchPathModePtr SetSearchPathModeFn = NULL;
SetDefaultDllDirectoriesPtr SetDefaultDllDirectoriesFn = NULL;
ImageList_CreatePtr ImageList_CreateFn = NULL;
ImageList_AddPtr ImageList_AddFn = NULL;
SetupCloseInfFilePtr SetupCloseInfFileFn = NULL;
SetupDiOpenClassRegKeyPtr SetupDiOpenClassRegKeyFn = NULL;
SetupInstallFromInfSectionWPtr SetupInstallFromInfSectionWFn = NULL;
SetupOpenInfFileWPtr SetupOpenInfFileWFn = NULL;
SHDeleteKeyWPtr SHDeleteKeyWFn = NULL;
SHStrDupWPtr SHStrDupWFn = NULL;
UrlUnescapeWPtr UrlUnescapeWFn = NULL;
ChangeWindowMessageFilterPtr ChangeWindowMessageFilterFn = NULL;
CreateProcessWithTokenWFn CreateProcessWithTokenWPtr = NULL;
typedef LONG (WINAPI *WINVERIFYTRUST)(HWND hwnd, GUID *pgActionID, LPVOID pWVTData);
typedef CRYPT_PROVIDER_DATA* (WINAPI *WTHELPERPROVDATAFROMSTATEDATA)(HANDLE hStateData);
typedef CRYPT_PROVIDER_SGNR* (WINAPI *WTHELPERGETPROVSIGNERFROMCHAIN)(CRYPT_PROVIDER_DATA *pProvData,
DWORD idxSigner,
BOOL fCounterSigner,
DWORD idxCounterSigner);
typedef CRYPT_PROVIDER_CERT* (WINAPI *WTHELPERGETPROVCERTFROMCHAIN)(CRYPT_PROVIDER_SGNR *pSgnr,
DWORD idxCert);
static WINVERIFYTRUST WinVerifyTrustFn = NULL;
static WTHELPERPROVDATAFROMSTATEDATA WTHelperProvDataFromStateDataFn = NULL;
static WTHELPERGETPROVSIGNERFROMCHAIN WTHelperGetProvSignerFromChainFn = NULL;
static WTHELPERGETPROVCERTFROMCHAIN WTHelperGetProvCertFromChainFn = NULL;
static unsigned char gpbSha256CodeSignCertFingerprint[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
};
typedef HRESULT (WINAPI *SHGETKNOWNFOLDERPATH) (
_In_ REFKNOWNFOLDERID rfid,
_In_ DWORD dwFlags,
_In_opt_ HANDLE hToken,
_Out_ PWSTR *ppszPath
);
/* 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;
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)
{
size_t i = wcslen (lpszSource);
if (i >= cbDest)
i = cbDest - 1;
lpszDest[i] = 0;
i++;
while (--i > 0)
{
lpszDest[i - 1] = (wchar_t) towupper (lpszSource[i - 1]);
}
}
}
std::wstring ToUpperCase (const std::wstring &str)
{
wstring u;
foreach (wchar_t c, str)
{
u += (wchar_t) towupper (c);
}
return u;
}
size_t TrimWhiteSpace(wchar_t *str)
{
wchar_t *end, *ptr = str;
size_t out_size;
if(!str || *str == 0)
return 0;
// Trim leading space
while(iswspace(*ptr)) ptr++;
if(*ptr == 0) // All spaces?
{
*str = 0;
return 0;
}
// Trim trailing space
end = str + wcslen(str) - 1;
while(end > ptr && iswspace(*end)) end--;
end++;
// Set output size to trimmed string length
out_size = (end - ptr);
// Copy trimmed string and add null terminator
wmemmove(str, ptr, out_size);
str[out_size] = 0;
return out_size;
}
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;
}
void AbortProcessDirect (wchar_t *abortMsg)
{
// Note that this function also causes localcleanup() to be called (see atexit())
MessageBeep (MB_ICONEXCLAMATION);
MessageBoxW (NULL, abortMsg, lpszTitle, ICON_HAND);
FREE_DLL (hRichEditDll);
FREE_DLL (hComctl32Dll);
FREE_DLL (hSetupDll);
FREE_DLL (hShlwapiDll);
FREE_DLL (hProfApiDll);
FREE_DLL (hUsp10Dll);
FREE_DLL (hCryptSpDll);
FREE_DLL (hUXThemeDll);
FREE_DLL (hUserenvDll);
FREE_DLL (hRsaenhDll);
FREE_DLL (himm32dll);
FREE_DLL (hMSCTFdll);
FREE_DLL (hfltlibdll);
FREE_DLL (hframedyndll);
FREE_DLL (hpsapidll);
FREE_DLL (hsecur32dll);
FREE_DLL (hnetapi32dll);
FREE_DLL (hauthzdll);
FREE_DLL (hxmllitedll);
FREE_DLL (hmprdll);
FREE_DLL (hsppdll);
FREE_DLL (vssapidll);
FREE_DLL (hvsstracedll);
FREE_DLL (hCryptSpDll);
FREE_DLL (hcfgmgr32dll);
FREE_DLL (hdevobjdll);
FREE_DLL (hpowrprofdll);
FREE_DLL (hsspiclidll);
FREE_DLL (hcryptbasedll);
FREE_DLL (hdwmapidll);
FREE_DLL (hmsasn1dll);
FREE_DLL (hcrypt32dll);
FREE_DLL (hbcryptdll);
FREE_DLL (hbcryptprimitivesdll);
FREE_DLL (hMsls31);
FREE_DLL (hntmartadll);
FREE_DLL (hwinscarddll);
FREE_DLL (hmsvcrtdll);
FREE_DLL (hAdvapi32Dll);
exit (1);
}
void AbortProcess (char *stringId)
{
// Note that this function also causes localcleanup() to be called (see atexit())
AbortProcessDirect (GetString (stringId));
}
void AbortProcessSilent (void)
{
FREE_DLL (hRichEditDll);
FREE_DLL (hComctl32Dll);
FREE_DLL (hSetupDll);
FREE_DLL (hShlwapiDll);
FREE_DLL (hProfApiDll);
FREE_DLL (hUsp10Dll);
FREE_DLL (hCryptSpDll);
FREE_DLL (hUXThemeDll);
FREE_DLL (hUserenvDll);
FREE_DLL (hRsaenhDll);
FREE_DLL (himm32dll);
FREE_DLL (hMSCTFdll);
FREE_DLL (hfltlibdll);
FREE_DLL (hframedyndll);
FREE_DLL (hpsapidll);
FREE_DLL (hsecur32dll);
FREE_DLL (hnetapi32dll);
FREE_DLL (hauthzdll);
FREE_DLL (hxmllitedll);
FREE_DLL (hmprdll);
FREE_DLL (hsppdll);
FREE_DLL (vssapidll);
FREE_DLL (hvsstracedll);
FREE_DLL (hCryptSpDll);
FREE_DLL (hcfgmgr32dll);
FREE_DLL (hdevobjdll);
FREE_DLL (hpowrprofdll);
FREE_DLL (hsspiclidll);
FREE_DLL (hcryptbasedll);
FREE_DLL (hdwmapidll);
FREE_DLL (hmsasn1dll);
FREE_DLL (hcrypt32dll);
FREE_DLL (hbcryptdll);
FREE_DLL (hbcryptprimitivesdll);
FREE_DLL (hMsls31);
FREE_DLL (hntmartadll);
FREE_DLL (hwinscarddll);
FREE_DLL (hmsvcrtdll);
FREE_DLL (hAdvapi32Dll);
// Note that this function also causes localcleanup() to be called (see atexit())
exit (1);
}
#pragma warning(push)
#pragma warning(disable:4702)
void *err_malloc (size_t size)
{
void *z = (void *) TCalloc (size);
if (z)
return z;
AbortProcess ("OUTOFMEMORY");
return 0;
}
#pragma warning(pop)
char *err_strdup (char *lpszText)
{
size_t j = (strlen (lpszText) + 1) * sizeof (char);
char *z = (char *) err_malloc (j);
memmove (z, lpszText, j);
return z;
}
BOOL IsDiskReadError (DWORD error)
{
return (error == ERROR_CRC
|| error == ERROR_IO_DEVICE
|| error == ERROR_BAD_CLUSTERS
|| error == ERROR_SECTOR_NOT_FOUND
|| error == ERROR_READ_FAULT
|| error == ERROR_INVALID_FUNCTION // I/O error may be reported as ERROR_INVALID_FUNCTION by buggy chipset drivers
|| error == ERROR_SEM_TIMEOUT); // I/O operation timeout may be reported as ERROR_SEM_TIMEOUT
}
BOOL IsDiskWriteError (DWORD error)
{
return (error == ERROR_IO_DEVICE
|| error == ERROR_BAD_CLUSTERS
|| error == ERROR_SECTOR_NOT_FOUND
|| error == ERROR_WRITE_FAULT
|| error == ERROR_INVALID_FUNCTION // I/O error may be reported as ERROR_INVALID_FUNCTION by buggy chipset drivers
|| error == ERROR_SEM_TIMEOUT); // I/O operation timeout may be reported as ERROR_SEM_TIMEOUT
}
BOOL IsDiskError (DWORD error)
{
return IsDiskReadError (error) || IsDiskWriteError (error);
}
DWORD handleWin32Error (HWND hwndDlg, const char* srcPos)
{
PWSTR lpMsgBuf;
DWORD dwError = GetLastError ();
wchar_t szErrorValue[32];
wchar_t* pszDesc;
if (Silent || dwError == 0 || dwError == ERROR_INVALID_WINDOW_HANDLE)
return dwError;
// Access denied
if (dwError == ERROR_ACCESS_DENIED && !IsAdmin ())
{
ErrorDirect ( AppendSrcPos (GetString ("ERR_ACCESS_DENIED"), srcPos).c_str (), hwndDlg);
SetLastError (dwError); // Preserve the original error code
return dwError;
}
FormatMessageW (
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dwError,
MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
(PWSTR) &lpMsgBuf,
0,
NULL
);
if (lpMsgBuf)
pszDesc = (wchar_t*) lpMsgBuf;
else
{
StringCchPrintfW (szErrorValue, ARRAYSIZE (szErrorValue), L"Error 0x%.8X", dwError);
pszDesc = szErrorValue;
}
MessageBoxW (hwndDlg, AppendSrcPos (pszDesc, srcPos).c_str (), lpszTitle, ICON_HAND);
if (lpMsgBuf) LocalFree (lpMsgBuf);
// User-friendly hardware error explanation
if (IsDiskError (dwError))
Error ("ERR_HARDWARE_ERROR", hwndDlg);
// Device not ready
if (dwError == ERROR_NOT_READY)
HandleDriveNotReadyError(hwndDlg);
SetLastError (dwError); // Preserve the original error code
return dwError;
}
BOOL translateWin32Error (wchar_t *lpszMsgBuf, int nWSizeOfBuf)
{
DWORD dwError = GetLastError ();
if (FormatMessageW (FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwError,
MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
lpszMsgBuf, nWSizeOfBuf, NULL))
{
SetLastError (dwError); // Preserve the original error code
return TRUE;
}
SetLastError (dwError); // Preserve the original error code
return FALSE;
}
// If the user has a non-default screen DPI, all absolute font sizes must be
// converted using this function.
int CompensateDPIFont (int val)
{
if (ScreenDPI == USER_DEFAULT_SCREEN_DPI)
return val;
else
{
double tmpVal = (double) val * DPIScaleFactorY * DlgAspectRatio * 0.999;
if (tmpVal > 0)
return (int) floor(tmpVal);
else
return (int) ceil(tmpVal);
}
}
// If the user has a non-default screen DPI, some screen coordinates and sizes must
// be converted using this function
int CompensateXDPI (int val)
{
if (ScreenDPI == USER_DEFAULT_SCREEN_DPI)
return val;
else
{
double tmpVal = (double) val * DPIScaleFactorX;
if (tmpVal > 0)
return (int) floor(tmpVal);
else
return (int) ceil(tmpVal);
}
}
// If the user has a non-default screen DPI, some screen coordinates and sizes must
// be converted using this function
int CompensateYDPI (int val)
{
if (ScreenDPI == USER_DEFAULT_SCREEN_DPI)
return val;
else
{
double tmpVal = (double) val * DPIScaleFactorY;
if (tmpVal > 0)
return (int) floor(tmpVal);
else
return (int) ceil(tmpVal);
}
}
int GetTextGfxWidth (HWND hwndDlgItem, const wchar_t *text, HFONT hFont)
{
SIZE sizes;
TEXTMETRIC textMetrics;
HDC hdc = GetDC (hwndDlgItem);
SelectObject(hdc, (HGDIOBJ) hFont);
GetTextExtentPoint32W (hdc, text, (int) wcslen (text), &sizes);
GetTextMetrics(hdc, &textMetrics); // Necessary for non-TrueType raster fonts (tmOverhang)
ReleaseDC (hwndDlgItem, hdc);
return ((int) sizes.cx - (int) textMetrics.tmOverhang);
}
int GetTextGfxHeight (HWND hwndDlgItem, const wchar_t *text, HFONT hFont)
{
SIZE sizes;
HDC hdc = GetDC (hwndDlgItem);
SelectObject(hdc, (HGDIOBJ) hFont);
GetTextExtentPoint32W (hdc, text, (int) wcslen (text), &sizes);
ReleaseDC (hwndDlgItem, hdc);
return ((int) sizes.cy);
}
std::wstring FitPathInGfxWidth (HWND hwnd, HFONT hFont, LONG width, const std::wstring &path)
{
wstring newPath;
RECT rect;
rect.left = 0;
rect.top = 0;
rect.right = width;
rect.bottom = LONG_MAX;
HDC hdc = GetDC (hwnd);
SelectObject (hdc, (HGDIOBJ) hFont);
wchar_t pathBuf[TC_MAX_PATH];
StringCchCopyW (pathBuf, ARRAYSIZE (pathBuf), path.c_str());
if (DrawText (hdc, pathBuf, (int) path.size(), &rect, DT_CALCRECT | DT_MODIFYSTRING | DT_PATH_ELLIPSIS | DT_SINGLELINE) != 0)
newPath = pathBuf;
ReleaseDC (hwnd, hdc);
return newPath;
}
static LRESULT CALLBACK HyperlinkProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
WNDPROC wp = (WNDPROC) GetWindowLongPtrW (hwnd, GWLP_USERDATA);
switch (message)
{
case WM_SETCURSOR:
if (!bHyperLinkBeingTracked)
{
TRACKMOUSEEVENT trackMouseEvent;
trackMouseEvent.cbSize = sizeof(trackMouseEvent);
trackMouseEvent.dwFlags = TME_LEAVE;
trackMouseEvent.hwndTrack = hwnd;
bHyperLinkBeingTracked = TrackMouseEvent(&trackMouseEvent);
HandCursor();
}
return 0;
case WM_MOUSELEAVE:
bHyperLinkBeingTracked = FALSE;
NormalCursor();
return 0;
}
return CallWindowProcW (wp, hwnd, message, wParam, lParam);
}
BOOL ToHyperlink (HWND hwndDlg, UINT ctrlId)
{
return ToCustHyperlink (hwndDlg, ctrlId, hUserUnderlineFont);
}
BOOL ToCustHyperlink (HWND hwndDlg, UINT ctrlId, HFONT hFont)
{
HWND hwndCtrl = GetDlgItem (hwndDlg, ctrlId);
SendMessageW (hwndCtrl, WM_SETFONT, (WPARAM) hFont, 0);
SetWindowLongPtrW (hwndCtrl, GWLP_USERDATA, (LONG_PTR) GetWindowLongPtrW (hwndCtrl, GWLP_WNDPROC));
SetWindowLongPtrW (hwndCtrl, GWLP_WNDPROC, (LONG_PTR) HyperlinkProc);
// Resize the field according to its actual size in pixels and move it if centered or right-aligned.
// This should be done again if the link text changes.
AccommodateTextField (hwndDlg, ctrlId, TRUE, hFont);
return TRUE;
}
// Resizes a text field according to its actual width and height in pixels (font size is taken into account) and moves
// it accordingly if the field is centered or right-aligned. Should be used on all hyperlinks upon dialog init
// after localization (bFirstUpdate should be TRUE) and later whenever a hyperlink text changes (bFirstUpdate
// must be FALSE).
void AccommodateTextField (HWND hwndDlg, UINT ctrlId, BOOL bFirstUpdate, HFONT hFont)
{
RECT rec, wrec, trec;
HWND hwndCtrl = GetDlgItem (hwndDlg, ctrlId);
int width, origWidth, height, origHeight;
int horizSubOffset, vertSubOffset, vertOffset, alignPosDiff = 0;
wchar_t text [MAX_URL_LENGTH];
WINDOWINFO windowInfo;
BOOL bBorderlessWindow = !(GetWindowLongPtrW (hwndDlg, GWL_STYLE) & (WS_BORDER | WS_DLGFRAME));
// Resize the field according to its length and font size and move if centered or right-aligned
GetWindowTextW (hwndCtrl, text, sizeof (text) / sizeof (wchar_t));
width = GetTextGfxWidth (hwndCtrl, text, hFont);
height = GetTextGfxHeight (hwndCtrl, text, hFont);
GetClientRect (hwndCtrl, &rec);
origWidth = rec.right;
origHeight = rec.bottom;
if (width >= 0
&& (!bFirstUpdate || origWidth > width)) // The original width of the field is the maximum allowed size
{
horizSubOffset = origWidth - width;
vertSubOffset = origHeight - height;
// Window coords
GetWindowRect(hwndDlg, &wrec);
GetClientRect(hwndDlg, &trec);
// Vertical "title bar" offset
vertOffset = wrec.bottom - wrec.top - trec.bottom - (bBorderlessWindow ? 0 : GetSystemMetrics(SM_CYFIXEDFRAME));
// Text field coords
GetWindowRect(hwndCtrl, &rec);
// Alignment offset
windowInfo.cbSize = sizeof(windowInfo);
GetWindowInfo (hwndCtrl, &windowInfo);
if (windowInfo.dwStyle & SS_CENTER)
alignPosDiff = horizSubOffset / 2;
else if (windowInfo.dwStyle & SS_RIGHT)
alignPosDiff = horizSubOffset;
// Resize/move
if (alignPosDiff > 0)
{
// Resize and move the text field
MoveWindow (hwndCtrl,
rec.left - wrec.left - (bBorderlessWindow ? 0 : GetSystemMetrics(SM_CXFIXEDFRAME)) + alignPosDiff,
rec.top - wrec.top - vertOffset,
origWidth - horizSubOffset,
origHeight - vertSubOffset,
TRUE);
}
else
{
// Resize the text field
SetWindowPos (hwndCtrl, 0, 0, 0,
origWidth - horizSubOffset,
origHeight - vertSubOffset,
SWP_NOMOVE | SWP_NOZORDER);
}
SetWindowPos (hwndCtrl, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
InvalidateRect (hwndCtrl, NULL, TRUE);
}
}
// Note that the user can still close the window by right-clicking its taskbar icon and selecting 'Close window', or by pressing Alt-F4, or using the Task Manager.
void DisableCloseButton (HWND hwndDlg)
{
EnableMenuItem (GetSystemMenu (hwndDlg, FALSE), SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED);
}
void EnableCloseButton (HWND hwndDlg)
{
EnableMenuItem (GetSystemMenu (hwndDlg, FALSE), SC_CLOSE, MF_BYCOMMAND | MF_ENABLED);
}
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-2022 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-2017 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-2017 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\r\n"
L"This software as a whole:\r\n"
L"Copyright \xA9 2013-2022 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;
}
static HWND StaticModelessWaitDlgHandle = NULL;
// Call DisplayStaticModelessWaitDlg() to open this dialog and CloseStaticModelessWaitDlg() to close it.
static BOOL CALLBACK StaticModelessWaitDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
WORD lw = LOWORD (wParam);
switch (msg)
{
case WM_INITDIALOG:
{
LocalizeDialog (hwndDlg, NULL);
return 0;
}
case WM_COMMAND:
if (lw == IDOK || lw == IDCANCEL)
return 1;
return 0;
case WM_CLOSE:
StaticModelessWaitDlgHandle = NULL;
EndDialog (hwndDlg, 0);
return 1;
}
return 0;
}
// Opens a dialog window saying "Please wait..." which is not modal and does not need any GUI refresh after initialization.
void DisplayStaticModelessWaitDlg (HWND parent)
{
if (StaticModelessWaitDlgHandle != NULL)
return; // Already shown
StaticModelessWaitDlgHandle = CreateDialogParamW (hInst, MAKEINTRESOURCEW (IDD_STATIC_MODELESS_WAIT_DLG), parent, (DLGPROC) StaticModelessWaitDlgProc, (LPARAM) 0);
ShowWindow (StaticModelessWaitDlgHandle, SW_SHOWNORMAL);
// Allow synchronous use with the GUI being instantly and fully rendered
ProcessPaintMessages (StaticModelessWaitDlgHandle, 500);
}
void CloseStaticModelessWaitDlg (void)
{
if (StaticModelessWaitDlgHandle == NULL)
return; // Not shown
DestroyWindow (StaticModelessWaitDlgHandle);
}
BOOL IsButtonChecked (HWND hButton)
{
if (SendMessage (hButton, BM_GETCHECK, 0, 0) == BST_CHECKED)
return TRUE;
else
return FALSE;
}
void CheckButton (HWND hButton)
{
SendMessage (hButton, BM_SETCHECK, BST_CHECKED, 0);
}
void LeftPadString (wchar_t *szTmp, int len, int targetLen, wchar_t filler)
{
int i;
if (targetLen <= len)
return;
for (i = targetLen-1; i >= (targetLen-len); i--)
szTmp [i] = szTmp [i-(targetLen-len)];
wmemset (szTmp, filler, targetLen-len);
szTmp [targetLen] = 0;
}
/* InitDialog - initialize the applications main dialog, this function should
be called only once in the dialogs WM_INITDIALOG message handler */
void InitDialog (HWND hwndDlg)
{
NONCLIENTMETRICSW metric;
static BOOL aboutMenuAppended = FALSE;
int nHeight;
LOGFONTW lf;
HMENU hMenu;
Font *font;
/* Fonts */
memset (&lf, 0, sizeof(lf));
// Normal
font = GetFont ("font_normal");
metric.cbSize = sizeof (metric);
SystemParametersInfoW (SPI_GETNONCLIENTMETRICS, sizeof(metric), &metric, 0);
WindowTitleBarFont = CreateFontIndirectW (&metric.lfCaptionFont);
metric.lfMessageFont.lfHeight = CompensateDPIFont (!font ? -11 : -font->Size);
metric.lfMessageFont.lfWidth = 0;
if (font && wcscmp (font->FaceName, L"default") != 0)
{
StringCbCopyW ((WCHAR *)metric.lfMessageFont.lfFaceName, sizeof (metric.lfMessageFont.lfFaceName), font->FaceName);
}
else if (IsOSAtLeast (WIN_VISTA))
{
// Vista's new default font (size and spacing) breaks compatibility with Windows 2k/XP applications.
// Force use of Tahoma (as Microsoft does in many dialogs) until a native Vista look is implemented.
StringCbCopyW ((WCHAR *)metric.lfMessageFont.lfFaceName, sizeof (metric.lfMessageFont.lfFaceName), L"Tahoma");
}
hUserFont = CreateFontIndirectW (&metric.lfMessageFont);
metric.lfMessageFont.lfUnderline = TRUE;
hUserUnderlineFont = CreateFontIndirectW (&metric.lfMessageFont);
metric.lfMessageFont.lfUnderline = FALSE;
metric.lfMessageFont.lfWeight = FW_BOLD;
hUserBoldFont = CreateFontIndirectW (&metric.lfMessageFont);
metric.lfMessageFont.lfUnderline = TRUE;
metric.lfMessageFont.lfWeight = FW_BOLD;
hUserUnderlineBoldFont = CreateFontIndirectW (&metric.lfMessageFont);
// Fixed-size (hexadecimal digits)
nHeight = CompensateDPIFont (-12);
lf.lfHeight = nHeight;
lf.lfWidth = 0;
lf.lfEscapement = 0;
lf.lfOrientation = 0;
lf.lfWeight = FW_NORMAL;
lf.lfItalic = FALSE;
lf.lfUnderline = FALSE;
lf.lfStrikeOut = FALSE;
lf.lfCharSet = DEFAULT_CHARSET;
lf.lfOutPrecision = OUT_DEFAULT_PRECIS;
lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
lf.lfQuality = PROOF_QUALITY;
lf.lfPitchAndFamily = FF_DONTCARE;
StringCbCopyW (lf.lfFaceName, sizeof(lf.lfFaceName), L"Courier New");
hFixedDigitFont = CreateFontIndirectW (&lf);
if (hFixedDigitFont == NULL)
{
handleWin32Error (hwndDlg, SRC_POS);
AbortProcess ("NOFONT");
}
// Bold
font = GetFont ("font_bold");
nHeight = CompensateDPIFont (!font ? -13 : -font->Size);
lf.lfHeight = nHeight;
lf.lfWeight = FW_BLACK;
StringCbCopyW (lf.lfFaceName, sizeof(lf.lfFaceName), !font ? L"Arial" : font->FaceName);
hBoldFont = CreateFontIndirectW (&lf);
if (hBoldFont == NULL)
{
handleWin32Error (hwndDlg, SRC_POS);
AbortProcess ("NOFONT");
}
// Title
font = GetFont ("font_title");
nHeight = CompensateDPIFont (!font ? -21 : -font->Size);
lf.lfHeight = nHeight;
lf.lfWeight = FW_REGULAR;
StringCbCopyW (lf.lfFaceName, sizeof(lf.lfFaceName),!font ? L"Times New Roman" : font->FaceName);
hTitleFont = CreateFontIndirectW (&lf);
if (hTitleFont == NULL)
{
handleWin32Error (hwndDlg, SRC_POS);
AbortProcess ("NOFONT");
}
// Fixed-size
font = GetFont ("font_fixed");
nHeight = CompensateDPIFont (!font ? -12 : -font->Size);
lf.lfHeight = nHeight;
lf.lfWidth = 0;
lf.lfEscapement = 0;
lf.lfOrientation = 0;
lf.lfWeight = FW_NORMAL;
lf.lfItalic = FALSE;
lf.lfUnderline = FALSE;
lf.lfStrikeOut = FALSE;
lf.lfCharSet = DEFAULT_CHARSET;
lf.lfOutPrecision = OUT_DEFAULT_PRECIS;
lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
lf.lfQuality = PROOF_QUALITY;
lf.lfPitchAndFamily = FF_DONTCARE;
StringCbCopyW (lf.lfFaceName, sizeof(lf.lfFaceName),!font ? L"Lucida Console" : font->FaceName);
hFixedFont = CreateFontIndirectW (&lf);
if (hFixedFont == NULL)
{
handleWin32Error (hwndDlg, SRC_POS);
AbortProcess ("NOFONT");
}
if (!aboutMenuAppended)
{
hMenu = GetSystemMenu (hwndDlg, FALSE);
AppendMenu (hMenu, MF_SEPARATOR, 0, L"");
AppendMenuW (hMenu, MF_ENABLED | MF_STRING, IDC_ABOUT, GetString ("ABOUTBOX"));
aboutMenuAppended = TRUE;
}
}
// The parameter maxMessagesToProcess prevents endless processing of paint messages
void ProcessPaintMessages (HWND hwnd, int maxMessagesToProcess)
{
MSG paintMsg;
int msgCounter = maxMessagesToProcess;
while (PeekMessageW (&paintMsg, hwnd, 0, 0, PM_REMOVE | PM_QS_PAINT) != 0 && msgCounter-- > 0)
{
DispatchMessageW (&paintMsg);
}
}
HDC CreateMemBitmap (HINSTANCE hInstance, HWND hwnd, wchar_t *resource)
{
HBITMAP picture = LoadBitmap (hInstance, resource);
HDC viewDC = GetDC (hwnd), dcMem;
dcMem = CreateCompatibleDC (viewDC);
SetMapMode (dcMem, MM_TEXT);
SelectObject (dcMem, picture);
DeleteObject (picture);
ReleaseDC (hwnd, viewDC);
return dcMem;
}
/* Renders the specified bitmap at the specified location and stretches it to fit (anti-aliasing is applied).
If bDirectRender is FALSE and both nWidth and nHeight are zero, the width and height of hwndDest are
retrieved and adjusted according to screen DPI (the width and height of the resultant image are adjusted the
same way); furthermore, if bKeepAspectRatio is TRUE, the smaller DPI factor of the two (i.e. horiz. or vert.)
is used both for horiz. and vert. scaling (note that the overall GUI aspect ratio changes irregularly in
both directions depending on the DPI). If bDirectRender is TRUE, bKeepAspectRatio is ignored.
This function returns a handle to the scaled bitmap. When the bitmap is no longer needed, it should be
deleted by calling DeleteObject() with the handle passed as the parameter.
Known Windows issues:
- For some reason, anti-aliasing is not applied if the source bitmap contains less than 16K pixels.
- Windows 2000 may produce slightly inaccurate colors even when source, buffer, and target are 24-bit true color. */
HBITMAP RenderBitmap (wchar_t *resource, HWND hwndDest, int x, int y, int nWidth, int nHeight, BOOL bDirectRender, BOOL bKeepAspectRatio)
{
LRESULT lResult = 0;
HDC hdcSrc = CreateMemBitmap (hInst, hwndDest, resource);
if (!hdcSrc)
return NULL;
HGDIOBJ picture = GetCurrentObject (hdcSrc, OBJ_BITMAP);
HBITMAP hbmpRescaled = NULL;
BITMAP bitmap;
HDC hdcRescaled;
if (!bDirectRender && nWidth == 0 && nHeight == 0)
{
RECT rec;
GetClientRect (hwndDest, &rec);
if (bKeepAspectRatio)
{
if (DlgAspectRatio > 1)
{
// Do not fix this, it's correct. We use the Y scale factor intentionally for both
// directions to maintain aspect ratio (see above for more info).
nWidth = CompensateYDPI (rec.right);
nHeight = CompensateYDPI (rec.bottom);
}
else
{
// Do not fix this, it's correct. We use the X scale factor intentionally for both
// directions to maintain aspect ratio (see above for more info).
nWidth = CompensateXDPI (rec.right);
nHeight = CompensateXDPI (rec.bottom);
}
}
else
{
nWidth = CompensateXDPI (rec.right);
nHeight = CompensateYDPI (rec.bottom);
}
}
GetObject (picture, sizeof (BITMAP), &bitmap);
hdcRescaled = CreateCompatibleDC (hdcSrc);
if (hdcRescaled)
{
hbmpRescaled = CreateCompatibleBitmap (hdcSrc, nWidth, nHeight);
SelectObject (hdcRescaled, hbmpRescaled);
/* Anti-aliasing mode (HALFTONE is the only anti-aliasing algorithm natively supported by Windows 2000.
TODO: GDI+ offers higher quality -- InterpolationModeHighQualityBicubic) */
SetStretchBltMode (hdcRescaled, HALFTONE);
StretchBlt (hdcRescaled,
0,
0,
nWidth,
nHeight,
hdcSrc,
0,
0,
bitmap.bmWidth,
bitmap.bmHeight,
SRCCOPY);
DeleteDC (hdcSrc);
if (bDirectRender)
{
HDC hdcDest = GetDC (hwndDest);
if (hdcDest)
{
BitBlt (hdcDest, x, y, nWidth, nHeight, hdcRescaled, 0, 0, SRCCOPY);
ReleaseDC (hwndDest, hdcDest);
}
}
else
{
lResult = SendMessage (hwndDest, (UINT) STM_SETIMAGE, (WPARAM) IMAGE_BITMAP, (LPARAM) (HANDLE) hbmpRescaled);
}
if ((HGDIOBJ) lResult != NULL && (HGDIOBJ) lResult != (HGDIOBJ) hbmpRescaled)
DeleteObject ((HGDIOBJ) lResult);
DeleteDC (hdcRescaled);
}
return hbmpRescaled;
}
LRESULT CALLBACK
RedTick (HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
if (uMsg == WM_CREATE)
{
}
else if (uMsg == WM_DESTROY)
{
}
else if (uMsg == WM_TIMER)
{
}
else if (uMsg == WM_PAINT)
{
PAINTSTRUCT tmp;
HPEN hPen;
HDC hDC;
BOOL bEndPaint;
RECT Rect;
if (GetUpdateRect (hwnd, NULL, FALSE))
{
hDC = BeginPaint (hwnd, &tmp);
bEndPaint = TRUE;
if (hDC == NULL)
return DefWindowProcW (hwnd, uMsg, wParam, lParam);
}
else
{
hDC = GetDC (hwnd);
bEndPaint = FALSE;
}
GetClientRect (hwnd, &Rect);
hPen = CreatePen (PS_SOLID, 2, RGB (0, 255, 0));
if (hPen != NULL)
{
HGDIOBJ hObj = SelectObject (hDC, hPen);
WORD bx = LOWORD (GetDialogBaseUnits ());
WORD by = HIWORD (GetDialogBaseUnits ());
MoveToEx (hDC, (Rect.right - Rect.left) / 2, Rect.bottom, NULL);
LineTo (hDC, Rect.right, Rect.top);
MoveToEx (hDC, (Rect.right - Rect.left) / 2, Rect.bottom, NULL);
LineTo (hDC, (3 * bx) / 4, (2 * by) / 8);
SelectObject (hDC, hObj);
DeleteObject (hPen);
}
if (bEndPaint)
EndPaint (hwnd, &tmp);
else
ReleaseDC (hwnd, hDC);
return TRUE;
}
return DefWindowProcW (hwnd, uMsg, wParam, lParam);
}
BOOL
RegisterRedTick (HINSTANCE hInstance)
{
WNDCLASSW wc;
ULONG rc;
memset(&wc, 0 , sizeof wc);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.cbClsExtra = 0;
wc.cbWndExtra = 4;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon (NULL, IDI_APPLICATION);
wc.hCursor = NULL;
wc.hbrBackground = (HBRUSH) GetStockObject (LTGRAY_BRUSH);
wc.lpszClassName = L"VCREDTICK";
wc.lpfnWndProc = &RedTick;
rc = (ULONG) RegisterClassW (&wc);
return rc == 0 ? FALSE : TRUE;
}
BOOL
UnregisterRedTick (HINSTANCE hInstance)
{
return UnregisterClassW (L"VCREDTICK", hInstance);
}
LRESULT CALLBACK
SplashDlgProc (HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
return DefDlgProcW (hwnd, uMsg, wParam, lParam);
}
static int g_waitCursorCounter = 0;
void
WaitCursor ()
{
static HCURSOR hcWait = 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;
byte *sp = (byte *) address;
if (codeEnd == 0)
{
MEMORY_BASIC_INFORMATION mi;
if (VirtualQuery ((LPCVOID) 0x401000, &mi, sizeof (mi)) >= sizeof (mi))
codeEnd = (size_t) mi.BaseAddress + mi.RegionSize;
}
if (address < 0x401000 + 8 || address > codeEnd)
return FALSE;
return sp[-5] == 0xe8 // call ADDR
|| (sp[-6] == 0xff && sp[-5] == 0x15) // call [ADDR]
|| (sp[-2] == 0xff && (sp[-1] & 0xf0) == 0xd0); // call REG
}
*/
typedef struct
{
EXCEPTION_POINTERS *ExceptionPointers;
HANDLE ExceptionThread;
} ExceptionHandlerThreadArgs;
void ExceptionHandlerThread (void *threadArg)
{
ExceptionHandlerThreadArgs *args = (ExceptionHandlerThreadArgs *) threadArg;
EXCEPTION_POINTERS *ep = args->ExceptionPointers;
//DWORD addr;
DWORD exCode = ep->ExceptionRecord->ExceptionCode;
// SYSTEM_INFO si;
// wchar_t msg[8192];
// char modPath[MAX_PATH];
// int crc = 0;
// char url[MAX_URL_LENGTH];
// char lpack[128];
// stringstream callStack;
// addr = (DWORD) ep->ExceptionRecord->ExceptionAddress;
// PDWORD sp = (PDWORD) ep->ContextRecord->Esp;
// int frameNumber = 0;
switch (exCode)
{
case STATUS_IN_PAGE_ERROR:
case 0xeedfade:
// Exception not caused by VeraCrypt
MessageBoxW (0, GetString ("EXCEPTION_REPORT_EXT"),
GetString ("EXCEPTION_REPORT_TITLE"),
MB_ICONERROR | MB_OK | MB_SETFOREGROUND | MB_TOPMOST);
return;
}
// Call stack
/* HMODULE dbgDll = LoadLibrary ("dbghelp.dll");
if (dbgDll)
{
typedef DWORD (__stdcall *SymGetOptions_t) ();
typedef DWORD (__stdcall *SymSetOptions_t) (DWORD SymOptions);
typedef BOOL (__stdcall *SymInitialize_t) (HANDLE hProcess, PCSTR UserSearchPath, BOOL fInvadeProcess);
typedef BOOL (__stdcall *StackWalk64_t) (DWORD MachineType, HANDLE hProcess, HANDLE hThread, LPSTACKFRAME64 StackFrame, PVOID ContextRecord, PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine, PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine, PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine, PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress);
typedef BOOL (__stdcall * SymFromAddr_t) (HANDLE hProcess, DWORD64 Address, PDWORD64 Displacement, PSYMBOL_INFO Symbol);
SymGetOptions_t DbgHelpSymGetOptions = (SymGetOptions_t) GetProcAddress (dbgDll, "SymGetOptions");
SymSetOptions_t DbgHelpSymSetOptions = (SymSetOptions_t) GetProcAddress (dbgDll, "SymSetOptions");
SymInitialize_t DbgHelpSymInitialize = (SymInitialize_t) GetProcAddress (dbgDll, "SymInitialize");
PFUNCTION_TABLE_ACCESS_ROUTINE64 DbgHelpSymFunctionTableAccess64 = (PFUNCTION_TABLE_ACCESS_ROUTINE64) GetProcAddress (dbgDll, "SymFunctionTableAccess64");
PGET_MODULE_BASE_ROUTINE64 DbgHelpSymGetModuleBase64 = (PGET_MODULE_BASE_ROUTINE64) GetProcAddress (dbgDll, "SymGetModuleBase64");
StackWalk64_t DbgHelpStackWalk64 = (StackWalk64_t) GetProcAddress (dbgDll, "StackWalk64");
SymFromAddr_t DbgHelpSymFromAddr = (SymFromAddr_t) GetProcAddress (dbgDll, "SymFromAddr");
if (DbgHelpSymGetOptions && DbgHelpSymSetOptions && DbgHelpSymInitialize && DbgHelpSymFunctionTableAccess64 && DbgHelpSymGetModuleBase64 && DbgHelpStackWalk64 && DbgHelpSymFromAddr)
{
DbgHelpSymSetOptions (DbgHelpSymGetOptions() | SYMOPT_DEFERRED_LOADS | SYMOPT_ALLOW_ABSOLUTE_SYMBOLS | SYMOPT_NO_CPP);
if (DbgHelpSymInitialize (GetCurrentProcess(), NULL, TRUE))
{
STACKFRAME64 frame;
memset (&frame, 0, sizeof (frame));
frame.AddrPC.Offset = ep->ContextRecord->Eip;
frame.AddrPC.Mode = AddrModeFlat;
frame.AddrStack.Offset = ep->ContextRecord->Esp;
frame.AddrStack.Mode = AddrModeFlat;
frame.AddrFrame.Offset = ep->ContextRecord->Ebp;
frame.AddrFrame.Mode = AddrModeFlat;
string lastSymbol;
while (frameNumber < 32 && DbgHelpStackWalk64 (IMAGE_FILE_MACHINE_I386, GetCurrentProcess(), args->ExceptionThread, &frame, ep->ContextRecord, NULL, DbgHelpSymFunctionTableAccess64, DbgHelpSymGetModuleBase64, NULL))
{
if (!frame.AddrPC.Offset)
continue;
ULONG64 symbolBuffer[(sizeof (SYMBOL_INFO) + MAX_SYM_NAME * sizeof (TCHAR) + sizeof (ULONG64) - 1) / sizeof (ULONG64)];
memset (symbolBuffer, 0, sizeof (symbolBuffer));
PSYMBOL_INFO symbol = (PSYMBOL_INFO) symbolBuffer;
symbol->SizeOfStruct = sizeof (SYMBOL_INFO);
symbol->MaxNameLen = MAX_SYM_NAME;
if (DbgHelpSymFromAddr (GetCurrentProcess(), frame.AddrPC.Offset, NULL, symbol) && symbol->NameLen > 0)
{
for (size_t i = 0; i < symbol->NameLen; ++i)
{
if (!isalnum (symbol->Name[i]))
symbol->Name[i] = '_';
}
if (symbol->Name != lastSymbol)
callStack << "&st" << frameNumber++ << "=" << symbol->Name;
lastSymbol = symbol->Name;
}
else if (frameNumber == 0 || IsReturnAddress (frame.AddrPC.Offset))
{
callStack << "&st" << frameNumber++ << "=0x" << hex << frame.AddrPC.Offset << dec;
}
}
}
}
}
// StackWalk64() may fail due to missing frame pointers
list <DWORD> retAddrs;
if (frameNumber == 0)
retAddrs.push_back (ep->ContextRecord->Eip);
retAddrs.push_back (0);
MEMORY_BASIC_INFORMATION mi;
VirtualQuery (sp, &mi, sizeof (mi));
PDWORD stackTop = (PDWORD)((byte *) mi.BaseAddress + mi.RegionSize);
int i = 0;
while (retAddrs.size() < 16 && &sp[i] < stackTop)
{
if (IsReturnAddress (sp[i]))
{
bool duplicate = false;
foreach (DWORD prevAddr, retAddrs)
{
if (sp[i] == prevAddr)
{
duplicate = true;
break;
}
}
if (!duplicate)
retAddrs.push_back (sp[i]);
}
i++;
}
if (retAddrs.size() > 1)
{
foreach (DWORD addr, retAddrs)
{
callStack << "&st" << frameNumber++ << "=0x" << hex << addr << dec;
}
}
// Checksum of the module
if (GetModuleFileName (NULL, modPath, sizeof (modPath)))
{
HANDLE h = CreateFile (modPath, FILE_READ_DATA | FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (h != INVALID_HANDLE_VALUE)
{
BY_HANDLE_FILE_INFORMATION fi;
if (GetFileInformationByHandle (h, &fi))
{
char *buf = (char *) malloc (fi.nFileSizeLow);
if (buf)
{
DWORD bytesRead;
if (ReadFile (h, buf, fi.nFileSizeLow, &bytesRead, NULL) && bytesRead == fi.nFileSizeLow)
crc = GetCrc32 ((unsigned char *) buf, fi.nFileSizeLow);
free (buf);
}
}
CloseHandle (h);
}
}
GetSystemInfo (&si);
if (LocalizationActive)
sprintf_s (lpack, sizeof (lpack), "&langpack=%s_%s", GetPreferredLangId (), GetActiveLangPackVersion ());
else
lpack[0] = 0;
sprintf (url, TC_APPLINK_SECURE "&dest=err-report%s&os=%s&osver=%d.%d.%d&arch=%s&cpus=%d&app=%s&cksum=%x&dlg=%s&err=%x&addr=%x"
, lpack
, GetWindowsEdition().c_str()
, CurrentOSMajor
, CurrentOSMinor
, CurrentOSServicePack
, Is64BitOs () ? "x64" : "x86"
, si.dwNumberOfProcessors
#ifdef TCMOUNT
,"main"
#endif
#ifdef VOLFORMAT
,"format"
#endif
#ifdef SETUP
,"setup"
#endif
, crc
, LastDialogId ? LastDialogId : "-"
, exCode
, addr);
string urlStr = url + callStack.str();
_snwprintf (msg, array_capacity (msg), GetString ("EXCEPTION_REPORT"), urlStr.c_str());
if (IDYES == MessageBoxW (0, msg, GetString ("EXCEPTION_REPORT_TITLE"), MB_ICONERROR | MB_YESNO | MB_DEFBUTTON1))
ShellExecute (NULL, "open", urlStr.c_str(), NULL, NULL, SW_SHOWNORMAL);
else */
UnhandledExceptionFilter (ep);
}
LONG __stdcall ExceptionHandler (EXCEPTION_POINTERS *ep)
{
SetUnhandledExceptionFilter (NULL);
if (SystemFileSelectorCallPending && SystemFileSelectorCallerThreadId == GetCurrentThreadId())
{
MessageBoxW (NULL, GetString ("EXCEPTION_REPORT_EXT_FILESEL"), GetString ("EXCEPTION_REPORT_TITLE"), MB_ICONERROR | MB_OK | MB_SETFOREGROUND | MB_TOPMOST);
UnhandledExceptionFilter (ep);
return EXCEPTION_EXECUTE_HANDLER;
}
ExceptionHandlerThreadArgs args;
args.ExceptionPointers = ep;
args.ExceptionThread = GetCurrentThread();
WaitForSingleObject ((HANDLE) _beginthread (ExceptionHandlerThread, 0, &args), INFINITE);
return EXCEPTION_EXECUTE_HANDLER;
}
void InvalidParameterHandler (const wchar_t *expression, const wchar_t *function, const wchar_t *file, unsigned int line, uintptr_t reserved)
{
TC_THROW_FATAL_EXCEPTION;
}
static LRESULT CALLBACK NonInstallUacWndProc (HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
return DefWindowProcW (hWnd, message, wParam, lParam);
}
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 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);
}
#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;
}
static void LoadSystemDll (LPCTSTR szModuleName, HMODULE *pHandle, BOOL bIgnoreError, const char* srcPos)
{
wchar_t dllPath[MAX_PATH];
/* Load dll explictely from System32 to avoid Dll hijacking attacks*/
if (!GetSystemDirectory(dllPath, MAX_PATH))
StringCbCopyW(dllPath, sizeof(dllPath), L"C:\\Windows\\System32");
StringCbCatW(dllPath, sizeof(dllPath), L"\\");
StringCbCatW(dllPath, sizeof(dllPath), szModuleName);
if (((*pHandle = LoadLibrary(dllPath)) == NULL) && !bIgnoreError)
{
// This error is fatal
handleWin32Error (NULL, srcPos);
AbortProcess ("INIT_DLL");
}
}
/* InitApp - initialize the application, this function is called once in the
applications WinMain function, but before the main dialog has been created */
void InitApp (HINSTANCE hInstance, wchar_t *lpszCommandLine)
{
WNDCLASSW wc;
char langId[6];
InitCommonControlsPtr InitCommonControlsFn = NULL;
wchar_t modPath[MAX_PATH];
GetModuleFileNameW (NULL, modPath, ARRAYSIZE (modPath));
/* remove current directory from dll search path */
SetDllDirectoryFn = (SetDllDirectoryPtr) GetProcAddress (GetModuleHandle(L"kernel32.dll"), "SetDllDirectoryW");
SetSearchPathModeFn = (SetSearchPathModePtr) GetProcAddress (GetModuleHandle(L"kernel32.dll"), "SetSearchPathMode");
SetDefaultDllDirectoriesFn = (SetDefaultDllDirectoriesPtr) GetProcAddress (GetModuleHandle(L"kernel32.dll"), "SetDefaultDllDirectories");
if (SetDllDirectoryFn)
SetDllDirectoryFn (L"");
if (SetSearchPathModeFn)
SetSearchPathModeFn (BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE | BASE_SEARCH_PATH_PERMANENT);
if (SetDefaultDllDirectoriesFn)
SetDefaultDllDirectoriesFn (LOAD_LIBRARY_SEARCH_SYSTEM32);
InitOSVersionInfo();
VirtualLock (&CmdTokenPin, sizeof (CmdTokenPin));
InitGlobalLocks ();
LoadSystemDll (L"msvcrt.dll", &hmsvcrtdll, TRUE, SRC_POS);
LoadSystemDll (L"ntmarta.dll", &hntmartadll, TRUE, SRC_POS);
LoadSystemDll (L"MPR.DLL", &hmprdll, TRUE, SRC_POS);
#ifdef SETUP
if (IsOSAtLeast (WIN_7))
{
LoadSystemDll (L"ProfApi.DLL", &hProfApiDll, TRUE, SRC_POS);
LoadSystemDll (L"cryptbase.dll", &hcryptbasedll, TRUE, SRC_POS);
LoadSystemDll (L"sspicli.dll", &hsspiclidll, TRUE, SRC_POS);
}
#endif
LoadSystemDll (L"psapi.dll", &hpsapidll, TRUE, SRC_POS);
LoadSystemDll (L"secur32.dll", &hsecur32dll, TRUE, SRC_POS);
LoadSystemDll (L"msasn1.dll", &hmsasn1dll, TRUE, SRC_POS);
LoadSystemDll (L"Usp10.DLL", &hUsp10Dll, TRUE, SRC_POS);
if (IsOSAtLeast (WIN_7))
LoadSystemDll (L"dwmapi.dll", &hdwmapidll, TRUE, SRC_POS);
LoadSystemDll (L"UXTheme.dll", &hUXThemeDll, TRUE, SRC_POS);
LoadSystemDll (L"msls31.dll", &hMsls31, TRUE, SRC_POS);
LoadSystemDll (L"SETUPAPI.DLL", &hSetupDll, FALSE, SRC_POS);
LoadSystemDll (L"SHLWAPI.DLL", &hShlwapiDll, FALSE, SRC_POS);
LoadSystemDll (L"userenv.dll", &hUserenvDll, TRUE, SRC_POS);
LoadSystemDll (L"rsaenh.dll", &hRsaenhDll, TRUE, SRC_POS);
#ifdef SETUP
if (nCurrentOS < WIN_7)
{
if (nCurrentOS == WIN_XP)
{
LoadSystemDll (L"imm32.dll", &himm32dll, TRUE, SRC_POS);
LoadSystemDll (L"MSCTF.dll", &hMSCTFdll, TRUE, SRC_POS);
LoadSystemDll (L"fltlib.dll", &hfltlibdll, TRUE, SRC_POS);
LoadSystemDll (L"wbem\\framedyn.dll", &hframedyndll, TRUE, SRC_POS);
}
if (IsOSAtLeast (WIN_VISTA))
{
LoadSystemDll (L"netapi32.dll", &hnetapi32dll, TRUE, SRC_POS);
LoadSystemDll (L"authz.dll", &hauthzdll, TRUE, SRC_POS);
LoadSystemDll (L"xmllite.dll", &hxmllitedll, TRUE, SRC_POS);
}
}
if (IsOSAtLeast (WIN_VISTA))
{
LoadSystemDll (L"atl.dll", &hsppdll, TRUE, SRC_POS);
LoadSystemDll (L"vsstrace.dll", &hvsstracedll, TRUE, SRC_POS);
LoadSystemDll (L"vssapi.dll", &vssapidll, TRUE, SRC_POS);
LoadSystemDll (L"spp.dll", &hsppdll, TRUE, SRC_POS);
}
#endif
LoadSystemDll (L"crypt32.dll", &hcrypt32dll, TRUE, SRC_POS);
if (IsOSAtLeast (WIN_7))
{
LoadSystemDll (L"CryptSP.dll", &hCryptSpDll, TRUE, SRC_POS);
LoadSystemDll (L"cfgmgr32.dll", &hcfgmgr32dll, TRUE, SRC_POS);
LoadSystemDll (L"devobj.dll", &hdevobjdll, TRUE, SRC_POS);
LoadSystemDll (L"powrprof.dll", &hpowrprofdll, TRUE, SRC_POS);
LoadSystemDll (L"bcrypt.dll", &hbcryptdll, TRUE, SRC_POS);
LoadSystemDll (L"bcryptprimitives.dll", &hbcryptprimitivesdll, TRUE, SRC_POS);
}
#ifndef SETUP
LoadSystemDll (L"WINSCARD.DLL", &hwinscarddll, TRUE, SRC_POS);
#endif
LoadSystemDll (L"COMCTL32.DLL", &hComctl32Dll, FALSE, SRC_POS);
// call InitCommonControls function
InitCommonControlsFn = (InitCommonControlsPtr) GetProcAddress (hComctl32Dll, "InitCommonControls");
ImageList_AddFn = (ImageList_AddPtr) GetProcAddress (hComctl32Dll, "ImageList_Add");
ImageList_CreateFn = (ImageList_CreatePtr) GetProcAddress (hComctl32Dll, "ImageList_Create");
if (InitCommonControlsFn && ImageList_AddFn && ImageList_CreateFn)
{
InitCommonControlsFn();
}
else
AbortProcess ("INIT_DLL");
LoadSystemDll (L"Riched20.dll", &hRichEditDll, FALSE, SRC_POS);
LoadSystemDll (L"Advapi32.dll", &hAdvapi32Dll, FALSE, SRC_POS);
#if !defined(SETUP)
if (!VerifyModuleSignature (modPath))
AbortProcess ("DIST_PACKAGE_CORRUPTED");
#endif
// Get SetupAPI functions pointers
SetupCloseInfFileFn = (SetupCloseInfFilePtr) GetProcAddress (hSetupDll, "SetupCloseInfFile");
SetupDiOpenClassRegKeyFn = (SetupDiOpenClassRegKeyPtr) GetProcAddress (hSetupDll, "SetupDiOpenClassRegKey");
SetupInstallFromInfSectionWFn = (SetupInstallFromInfSectionWPtr) GetProcAddress (hSetupDll, "SetupInstallFromInfSectionW");
SetupOpenInfFileWFn = (SetupOpenInfFileWPtr) GetProcAddress (hSetupDll, "SetupOpenInfFileW");
if (!SetupCloseInfFileFn || !SetupDiOpenClassRegKeyFn || !SetupInstallFromInfSectionWFn || !SetupOpenInfFileWFn)
AbortProcess ("INIT_DLL");
// Get SHDeleteKeyW,SHStrDupW, UrlUnescapeW functions pointers
SHDeleteKeyWFn = (SHDeleteKeyWPtr) GetProcAddress (hShlwapiDll, "SHDeleteKeyW");
SHStrDupWFn = (SHStrDupWPtr) GetProcAddress (hShlwapiDll, "SHStrDupW");
UrlUnescapeWFn = (UrlUnescapeWPtr) GetProcAddress(hShlwapiDll, "UrlUnescapeW");
if (!SHDeleteKeyWFn || !SHStrDupWFn || !UrlUnescapeWFn)
AbortProcess ("INIT_DLL");
if (IsOSAtLeast (WIN_VISTA))
{
/* Get ChangeWindowMessageFilter used to enable some messages bypasss UIPI (User Interface Privilege Isolation) */
ChangeWindowMessageFilterFn = (ChangeWindowMessageFilterPtr) GetProcAddress (GetModuleHandle (L"user32.dll"), "ChangeWindowMessageFilter");
#ifndef SETUP
/* enable drag-n-drop when we are running elevated */
AllowMessageInUIPI (WM_DROPFILES);
AllowMessageInUIPI (WM_COPYDATA);
AllowMessageInUIPI (WM_COPYGLOBALDATA);
#endif
}
// Get CreateProcessWithTokenW function pointer
CreateProcessWithTokenWPtr = (CreateProcessWithTokenWFn) GetProcAddress(hAdvapi32Dll, "CreateProcessWithTokenW");
/* Save the instance handle for later */
hInst = hInstance;
SetErrorMode (SetErrorMode (0) | SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
CoInitialize (NULL);
#ifndef SETUP
// Application ID
typedef HRESULT (WINAPI *SetAppId_t) (PCWSTR appID);
SetAppId_t setAppId = (SetAppId_t) GetProcAddress (GetModuleHandle (L"shell32.dll"), "SetCurrentProcessExplicitAppUserModelID");
if (setAppId)
setAppId (TC_APPLICATION_ID);
#endif
// Language
langId[0] = 0;
SetPreferredLangId (ConfigReadString ("Language", "", langId, sizeof (langId)));
#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 Vista, Windows 7, Windows 8/8.1
if ( !IsOSVersionAtLeast(WIN_VISTA, 0)
#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
else
{
// Service pack check & warnings about critical MS issues
switch (nCurrentOS)
{
case WIN_XP:
if (CurrentOSServicePack < 1)
{
HKEY k;
// PE environment does not report version of SP
if (RegOpenKeyExW (HKEY_LOCAL_MACHINE, L"System\\CurrentControlSet\\Control\\minint", 0, KEY_READ, &k) != ERROR_SUCCESS)
Warning ("LARGE_IDE_WARNING_XP", NULL);
else
RegCloseKey (k);
}
break;
}
}
/* Get the attributes for the standard dialog class */
if ((GetClassInfoW (hInst, WINDOWS_DIALOG_CLASS, &wc)) == 0)
{
handleWin32Error (NULL, SRC_POS);
AbortProcess ("INIT_REGISTER");
}
#ifndef SETUP
wc.hIcon = LoadIcon (hInstance, MAKEINTRESOURCE (IDI_TRUECRYPT_ICON));
#else
#include "../setup/resource.h"
wc.hIcon = LoadIcon (hInstance, MAKEINTRESOURCE (IDI_SETUP));
#endif
wc.lpszClassName = TC_DLG_CLASS;
wc.lpfnWndProc = &CustomDlgProc;
wc.hCursor = LoadCursor (NULL, IDC_ARROW);
wc.cbWndExtra = DLGWINDOWEXTRA;
hDlgClass = RegisterClassW (&wc);
if (hDlgClass == 0)
{
handleWin32Error (NULL, SRC_POS);
AbortProcess ("INIT_REGISTER");
}
wc.lpszClassName = TC_SPLASH_CLASS;
wc.lpfnWndProc = &SplashDlgProc;
wc.hCursor = LoadCursor (NULL, IDC_ARROW);
wc.cbWndExtra = DLGWINDOWEXTRA;
hSplashClass = RegisterClassW (&wc);
if (hSplashClass == 0)
{
handleWin32Error (NULL, SRC_POS);
AbortProcess ("INIT_REGISTER");
}
// DPI and GUI aspect ratio
DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_AUXILIARY_DLG), NULL,
(DLGPROC) AuxiliaryDlgProc, (LPARAM) 1);
InitHelpFileName ();
#ifndef SETUP
#ifdef _WIN64
if (IsOSAtLeast (WIN_7))
{
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);
FREE_DLL (hRichEditDll);
FREE_DLL (hComctl32Dll);
FREE_DLL (hSetupDll);
FREE_DLL (hShlwapiDll);
FREE_DLL (hProfApiDll);
FREE_DLL (hUsp10Dll);
FREE_DLL (hCryptSpDll);
FREE_DLL (hUXThemeDll);
FREE_DLL (hUserenvDll);
FREE_DLL (hRsaenhDll);
FREE_DLL (himm32dll);
FREE_DLL (hMSCTFdll);
FREE_DLL (hfltlibdll);
FREE_DLL (hframedyndll);
FREE_DLL (hpsapidll);
FREE_DLL (hsecur32dll);
FREE_DLL (hnetapi32dll);
FREE_DLL (hauthzdll);
FREE_DLL (hxmllitedll);
FREE_DLL (hmprdll);
FREE_DLL (hsppdll);
FREE_DLL (vssapidll);
FREE_DLL (hvsstracedll);
FREE_DLL (hCryptSpDll);
FREE_DLL (hcfgmgr32dll);
FREE_DLL (hdevobjdll);
FREE_DLL (hpowrprofdll);
FREE_DLL (hsspiclidll);
FREE_DLL (hcryptbasedll);
FREE_DLL (hdwmapidll);
FREE_DLL (hmsasn1dll);
FREE_DLL (hcrypt32dll);
FREE_DLL (hbcryptdll);
FREE_DLL (hbcryptprimitivesdll);
FREE_DLL (hMsls31);
FREE_DLL (hntmartadll);
FREE_DLL (hwinscarddll);
FREE_DLL (hmsvcrtdll);
FREE_DLL (hAdvapi32Dll);
exit (1);
}
#endif
}
void FinalizeApp (void)
{
FREE_DLL (hRichEditDll);
FREE_DLL (hComctl32Dll);
FREE_DLL (hSetupDll);
FREE_DLL (hShlwapiDll);
FREE_DLL (hProfApiDll);
FREE_DLL (hUsp10Dll);
FREE_DLL (hCryptSpDll);
FREE_DLL (hUXThemeDll);
FREE_DLL (hUserenvDll);
FREE_DLL (hRsaenhDll);
FREE_DLL (himm32dll);
FREE_DLL (hMSCTFdll);
FREE_DLL (hfltlibdll);
FREE_DLL (hframedyndll);
FREE_DLL (hpsapidll);
FREE_DLL (hsecur32dll);
FREE_DLL (hnetapi32dll);
FREE_DLL (hauthzdll);
FREE_DLL (hxmllitedll);
FREE_DLL (hmprdll);
FREE_DLL (hsppdll);
FREE_DLL (vssapidll);
FREE_DLL (hvsstracedll);
FREE_DLL (hCryptSpDll);
FREE_DLL (hcfgmgr32dll);
FREE_DLL (hdevobjdll);
FREE_DLL (hpowrprofdll);
FREE_DLL (hsspiclidll);
FREE_DLL (hcryptbasedll);
FREE_DLL (hdwmapidll);
FREE_DLL (hmsasn1dll);
FREE_DLL (hcrypt32dll);
FREE_DLL (hbcryptdll);
FREE_DLL (hbcryptprimitivesdll);
FREE_DLL (hMsls31);
FREE_DLL (hntmartadll);
FREE_DLL (hwinscarddll);
FREE_DLL (hmsvcrtdll);
FREE_DLL (hAdvapi32Dll);
}
void InitHelpFileName (void)
{
wchar_t *lpszTmp;
GetModuleFileNameW (NULL, szHelpFile, ARRAYSIZE (szHelpFile));
lpszTmp = wcsrchr (szHelpFile, L'\\');
if (lpszTmp)
{
wchar_t szTemp[TC_MAX_PATH];
++lpszTmp;
*lpszTmp = 0; // add null terminating character to prepare for append operations
// Primary file name
if (strcmp (GetPreferredLangId(), "en") == 0
|| strlen(GetPreferredLangId()) == 0)
{
StringCbCatW (szHelpFile, sizeof(szHelpFile), L"docs\\VeraCrypt User Guide.chm");
}
else
{
StringCbPrintfW (szTemp, sizeof(szTemp), L"docs\\VeraCrypt User Guide.%S.chm", GetPreferredLangId());
StringCbCatW (szHelpFile, sizeof(szHelpFile), szTemp);
}
// Secondary file name (used when localized documentation is not found).
GetModuleFileNameW (NULL, szHelpFile2, ARRAYSIZE (szHelpFile2));
lpszTmp = wcsrchr (szHelpFile2, L'\\');
if (lpszTmp)
{
++lpszTmp;
*lpszTmp = 0;
StringCbCatW (szHelpFile2, sizeof(szHelpFile2), L"docs\\VeraCrypt User Guide.chm");
}
}
}
#ifndef SETUP
BOOL OpenDevice (const wchar_t *lpszPath, OPEN_TEST_STRUCT *driver, BOOL detectFilesystem, BOOL computeVolumeIDs)
{
DWORD dwResult;
BOOL bResult;
wchar_t wszFileName[TC_MAX_PATH];
StringCbCopyW (wszFileName, sizeof(wszFileName), lpszPath);
memset (driver, 0, sizeof (OPEN_TEST_STRUCT));
memcpy (driver->wszFileName, wszFileName, sizeof (wszFileName));
driver->bDetectTCBootLoader = FALSE;
driver->DetectFilesystem = detectFilesystem;
driver->bComputeVolumeIDs = computeVolumeIDs;
bResult = DeviceIoControl (hDriver, TC_IOCTL_OPEN_TEST,
driver, sizeof (OPEN_TEST_STRUCT),
driver, sizeof (OPEN_TEST_STRUCT),
&dwResult, NULL);
// check variable driver
if ( bResult
&& ( (driver->bDetectTCBootLoader != TRUE && driver->bDetectTCBootLoader != FALSE) ||
(driver->TCBootLoaderDetected != TRUE && driver->TCBootLoaderDetected != FALSE) ||
(driver->DetectFilesystem != TRUE && driver->DetectFilesystem != FALSE) ||
(driver->FilesystemDetected != TRUE && driver->FilesystemDetected != FALSE) ||
(wcscmp (wszFileName, driver->wszFileName))
)
)
{
return FALSE;
}
if (bResult == FALSE)
{
dwResult = GetLastError ();
if (dwResult == ERROR_SHARING_VIOLATION || dwResult == ERROR_NOT_READY)
{
driver->TCBootLoaderDetected = FALSE;
driver->FilesystemDetected = FALSE;
memset (driver->VolumeIDComputed, 0, sizeof (driver->VolumeIDComputed));
return TRUE;
}
else
return FALSE;
}
return TRUE;
}
#endif
// Tells the driver that it's running in portable mode
void NotifyDriverOfPortableMode (void)
{
if (hDriver != INVALID_HANDLE_VALUE)
{
DWORD dwResult;
DeviceIoControl (hDriver, TC_IOCTL_SET_PORTABLE_MODE_STATUS, NULL, 0, NULL, 0, &dwResult, NULL);
}
}
BOOL GetDriveLabel (int driveNo, wchar_t *label, int labelSize)
{
DWORD fileSystemFlags;
wchar_t root[] = { L'A' + (wchar_t) driveNo, L':', L'\\', 0 };
return GetVolumeInformationW (root, label, labelSize / 2, NULL, NULL, &fileSystemFlags, NULL, 0);
}
#ifndef SETUP
/* Stores the device path of the system partition in SysPartitionDevicePath and the device path of the system drive
in SysDriveDevicePath.
IMPORTANT: As this may take a very long time if called for the first time, it should be called only before performing
a dangerous operation (such as header backup restore or formatting a supposedly non-system device) never
at WM_INITDIALOG or any other GUI events -- instead call IsSystemDevicePath (path, hwndDlg, FALSE) for
very fast preliminary GUI checks; also note that right after the "Select Device" dialog exits with an OK
return code, you can use the global flags bSysPartitionSelected and bSysDriveSelected to see if the user
selected the system partition/device.
After this function completes successfully, the results are cached for the rest of the session and repeated
executions complete very fast. Returns TRUE if successful (otherwise FALSE). */
BOOL GetSysDevicePaths (HWND hwndDlg)
{
if (!bCachedSysDevicePathsValid
|| wcslen (SysPartitionDevicePath) <= 1
|| wcslen (SysDriveDevicePath) <= 1)
{
foreach (const HostDevice &device, GetAvailableHostDevices (false, true))
{
if (device.ContainsSystem)
StringCchCopyW (device.IsPartition ? SysPartitionDevicePath : SysDriveDevicePath, TC_MAX_PATH, device.Path.c_str());
}
if (IsOSAtLeast (WIN_7))
{
// Find extra boot partition
foreach (const HostDevice &drive, GetAvailableHostDevices (false, false))
{
if (drive.ContainsSystem)
{
foreach (const HostDevice &sysDrivePartition, drive.Partitions)
{
if (sysDrivePartition.Bootable)
{
if (sysDrivePartition.Size <= TC_MAX_EXTRA_BOOT_PARTITION_SIZE)
ExtraBootPartitionDevicePath = sysDrivePartition.Path;
break;
}
}
break;
}
}
}
bCachedSysDevicePathsValid = 1;
}
return (bCachedSysDevicePathsValid
&& wcslen (SysPartitionDevicePath) > 1
&& wcslen (SysDriveDevicePath) > 1);
}
/* Determines whether the device path is the path of the system partition or of the system drive (or neither).
If bReliableRequired is TRUE, very fast execution is guaranteed, but the results cannot be relied upon.
If it's FALSE and the function is called for the first time, execution may take up to one minute but the
results are reliable.
IMPORTANT: As the execution may take a very long time if called for the first time with bReliableRequired set
to TRUE, it should be called with bReliableRequired set to TRUE only before performing a dangerous
operation (such as header backup restore or formatting a supposedly non-system device) never at
WM_INITDIALOG or any other GUI events (use IsSystemDevicePath(path, hwndDlg, FALSE) for fast
preliminary GUI checks; also note that right after the "Select Device" dialog exits with an OK
return code, you can use the global flags bSysPartitionSelected and bSysDriveSelected to see if the
user selected the system partition/device).
After this function completes successfully, the results are cached for the rest of the session, bReliableRequired
is ignored (TRUE implied), repeated executions complete very fast, and the results are always reliable.
Return codes:
1 - it is the system partition path (e.g. \Device\Harddisk0\Partition1)
2 - it is the system drive path (e.g. \Device\Harddisk0\Partition0)
3 - it is the extra boot partition path
0 - it's not the system partition/drive path
-1 - the result can't be determined, isn't reliable, or there was an error. */
int IsSystemDevicePath (const wchar_t *path, HWND hwndDlg, BOOL bReliableRequired)
{
if (!bCachedSysDevicePathsValid
&& bReliableRequired)
{
if (!GetSysDevicePaths (hwndDlg))
return -1;
}
if (wcslen (SysPartitionDevicePath) <= 1 || wcslen (SysDriveDevicePath) <= 1)
return -1;
if (!path)
return -1;
if (wcsncmp (path, SysPartitionDevicePath, max (wcslen(path), wcslen(SysPartitionDevicePath))) == 0)
return 1;
else if (wcsncmp (path, SysDriveDevicePath, max (wcslen(path), wcslen(SysDriveDevicePath))) == 0)
return 2;
else if (ExtraBootPartitionDevicePath == path)
return 3;
return 0;
}
/* Determines whether the path points to a non-system partition on the system drive.
IMPORTANT: As this may take a very long time if called for the first time, it should be called
only before performing a dangerous operation, never at WM_INITDIALOG or any other GUI events.
Return codes:
0 - it isn't a non-system partition on the system drive
1 - it's a non-system partition on the system drive
-1 - the result can't be determined, isn't reliable, or there was an error. */
int IsNonSysPartitionOnSysDrive (const wchar_t *path)
{
wchar_t tmpPath [TC_MAX_PATH + 1];
int pos;
if (!GetSysDevicePaths (MainDlg))
return -1;
if (wcslen (SysPartitionDevicePath) <= 1 || wcslen (SysDriveDevicePath) <= 1)
return -1;
if (wcsncmp (path, SysPartitionDevicePath, max (wcslen(path), wcslen(SysPartitionDevicePath))) == 0
|| wcsncmp (path, SysDriveDevicePath, max (wcslen(path), wcslen(SysDriveDevicePath))) == 0)
{
// It is the system partition/drive path (it isn't a non-system partition)
return 0;
}
memset (tmpPath, 0, sizeof (tmpPath));
wcsncpy (tmpPath, path, ARRAYSIZE (tmpPath) - 1);
pos = (int) FindString ((const char*) tmpPath, (const char*) L"Partition", (int) wcslen (tmpPath) * 2, (int) wcslen (L"Partition") * 2, 0);
if (pos < 0)
return -1;
pos /= 2;
pos += (int) strlen ("Partition");
if (pos + 1 > ARRAYSIZE (tmpPath) - 1)
return -1;
tmpPath [pos] = L'0';
tmpPath [pos + 1] = 0;
if (wcsncmp (tmpPath, SysDriveDevicePath, max (wcslen(tmpPath), wcslen(SysDriveDevicePath))) == 0)
{
// It is a non-system partition on the system drive
return 1;
}
else
{
// The partition is not on the system drive
return 0;
}
}
#endif //!SETUP
wstring GetSysEncryptionPretestInfo2String (void)
{
// This huge string is divided into smaller portions to make it easier for translators to
// re-translate it when a minor modification is made to it (the whole huge string will not be
// reverted to English, so they will have to translate only a small portion of it).
return (wstring (L"\n")
+ GetString ("SYS_ENCRYPTION_PRETEST_INFO2_PORTION_1")
+ GetString ("SYS_ENCRYPTION_PRETEST_INFO2_PORTION_2")
+ GetString ("SYS_ENCRYPTION_PRETEST_INFO2_PORTION_3")
+ GetString ("SYS_ENCRYPTION_PRETEST_INFO2_PORTION_4"));
}
wstring GetRescueDiskHelpString (void)
{
// This huge string is divided into smaller portions to make it easier for translators to
// re-translate it when a minor modification is made to it (the whole huge string will not be
// reverted to English, so they will have to translate only a small portion of it).
return (wstring (
GetString ("RESCUE_DISK_HELP_PORTION_1"))
+ GetString ("RESCUE_DISK_HELP_PORTION_2")
+ GetString ("RESCUE_DISK_HELP_PORTION_3")
+ GetString ("RESCUE_DISK_HELP_PORTION_4")
+ GetString ("RESCUE_DISK_HELP_PORTION_5")
+ GetString ("RESCUE_DISK_HELP_PORTION_6")
+ GetString ("RESCUE_DISK_HELP_PORTION_7")
+ GetString ("RESCUE_DISK_HELP_PORTION_8")
+ GetString ("RESCUE_DISK_HELP_PORTION_9"));
}
wstring GetDecoyOsInstructionsString (void)
{
// This huge string is divided into smaller portions to make it easier for translators to
// re-translate it when a minor modification is made to it (the whole huge string will not be
// reverted to English, so they will have to translate only a small portion of it).
return (wstring (
GetString ("DECOY_OS_INSTRUCTIONS_PORTION_1"))
+ GetString ("DECOY_OS_INSTRUCTIONS_PORTION_2")
+ GetString ("DECOY_OS_INSTRUCTIONS_PORTION_3")
+ GetString ("DECOY_OS_INSTRUCTIONS_PORTION_4")
+ GetString ("DECOY_OS_INSTRUCTIONS_PORTION_5")
+ GetString ("DECOY_OS_INSTRUCTIONS_PORTION_6")
+ GetString ("DECOY_OS_INSTRUCTIONS_PORTION_7")
+ GetString ("DECOY_OS_INSTRUCTIONS_PORTION_8")
+ GetString ("DECOY_OS_INSTRUCTIONS_PORTION_9")
+ GetString ("DECOY_OS_INSTRUCTIONS_PORTION_10")
+ GetString ("DECOY_OS_INSTRUCTIONS_PORTION_11")
+ GetString ("DECOY_OS_INSTRUCTIONS_PORTION_12")
+ GetString ("DECOY_OS_INSTRUCTIONS_PORTION_13")
+ GetString ("DECOY_OS_INSTRUCTIONS_PORTION_14")
+ GetString ("DECOY_OS_INSTRUCTIONS_PORTION_15")
+ GetString ("DECOY_OS_INSTRUCTIONS_PORTION_16")
+ GetString ("DECOY_OS_INSTRUCTIONS_PORTION_17")
+ GetString ("DECOY_OS_INSTRUCTIONS_PORTION_18"));
}
struct _TEXT_EDIT_DIALOG_PARAM {
BOOL ReadOnly;
std::string&