diff options
Diffstat (limited to 'src/Mount/Mount.c')
-rw-r--r-- | src/Mount/Mount.c | 2244 |
1 files changed, 1708 insertions, 536 deletions
diff --git a/src/Mount/Mount.c b/src/Mount/Mount.c index 4333bb65..76de34b6 100644 --- a/src/Mount/Mount.c +++ b/src/Mount/Mount.c @@ -48,23 +48,47 @@ #include "../Common/SecurityToken.h" #include "../Platform/Finally.h" #include "../Platform/ForEach.h" +#include "../Setup/SelfExtract.h" +#include "../Common/EncryptionThreadPool.h" #include <Strsafe.h> +#include <InitGuid.h> +#include <devguid.h> +#include <devpkey.h> +#include <SetupAPI.h> +#include <Cfgmgr32.h> +#include <intrin.h> +#include <vector> +#include <algorithm> -#import <msxml6.dll> +#pragma intrinsic(_InterlockedCompareExchange, _InterlockedExchange) + +#import <msxml6.dll> no_auto_exclude #include <wtsapi32.h> typedef BOOL (WINAPI *WTSREGISTERSESSIONNOTIFICATION)(HWND, DWORD); typedef BOOL (WINAPI *WTSUNREGISTERSESSIONNOTIFICATION)(HWND); +#ifndef _HPOWERNOTIFY_DEF_ +#define _HPOWERNOTIFY_DEF_ + +typedef PVOID HPOWERNOTIFY; +typedef HPOWERNOTIFY *PHPOWERNOTIFY; + +#endif + +typedef HPOWERNOTIFY (WINAPI *REGISTERSUSPENDRESUMENOTIFICATION)(HANDLE hRecipient, DWORD Flags); +typedef BOOL (WINAPI *UNREGISTERSUSPENDRESUMENOTIFICATION) (HPOWERNOTIFY Handle); + using namespace VeraCrypt; enum timer_ids { TIMER_ID_MAIN = 0xff, TIMER_ID_KEYB_LAYOUT_GUARD, - TIMER_ID_UPDATE_DEVICE_LIST + TIMER_ID_UPDATE_DEVICE_LIST, + TIMER_ID_CHECK_FOREGROUND }; enum hidden_os_read_only_notif_mode @@ -77,6 +101,7 @@ enum hidden_os_read_only_notif_mode #define TIMER_INTERVAL_MAIN 500 #define TIMER_INTERVAL_KEYB_LAYOUT_GUARD 10 #define TIMER_INTERVAL_UPDATE_DEVICE_LIST 1000 +#define TIMER_INTERVAL_CHECK_FOREGROUND 500 BootEncryption *BootEncObj = NULL; BootEncryptionStatus BootEncStatus; @@ -142,27 +167,26 @@ int CmdVolumePkcs5 = 0; int VolumePim = -1; int CmdVolumePim = -1; int DefaultVolumePkcs5 = 0; -BOOL VolumeTrueCryptMode = FALSE; -BOOL CmdVolumeTrueCryptMode = FALSE; -BOOL DefaultVolumeTrueCryptMode = FALSE; BOOL CmdVolumePasswordValid = FALSE; MountOptions CmdMountOptions; BOOL CmdMountOptionsValid = FALSE; MountOptions mountOptions; MountOptions defaultMountOptions; -KeyFile *FirstCmdKeyFile; +KeyFile *FirstCmdKeyFile = NULL; HBITMAP hbmLogoBitmapRescaled = NULL; wchar_t OrigKeyboardLayout [8+1] = L"00000409"; BOOL bKeyboardLayoutChanged = FALSE; /* TRUE if the keyboard layout was changed to the standard US keyboard layout (from any other layout). */ BOOL bKeybLayoutAltKeyWarningShown = FALSE; /* TRUE if the user has been informed that it is not possible to type characters by pressing keys while the right Alt key is held down. */ -static KeyFilesDlgParam hidVolProtKeyFilesParam; +static KeyFilesDlgParam hidVolProtKeyFilesParam = {0}; static MOUNT_LIST_STRUCT LastKnownMountList = {0}; VOLUME_NOTIFICATIONS_LIST VolumeNotificationsList; static DWORD LastKnownLogicalDrives; +static volatile LONG FavoriteMountOnGoing = 0; + static HANDLE TaskBarIconMutex = NULL; static BOOL MainWindowHidden = FALSE; static int pwdChangeDlgMode = PCDM_CHANGE_PASSWORD; @@ -171,12 +195,20 @@ static int bPrebootPasswordDlgMode = FALSE; static int NoCmdLineArgs; static BOOL CmdLineVolumeSpecified; static int LastDriveListVolumeColumnWidth; +static BOOL ExitMailSlotSpecified = FALSE; +static TCHAR ExitMailSlotName[MAX_PATH]; // WTS handling static HMODULE hWtsLib = NULL; static WTSREGISTERSESSIONNOTIFICATION fnWtsRegisterSessionNotification = NULL; static WTSUNREGISTERSESSIONNOTIFICATION fnWtsUnRegisterSessionNotification = NULL; -static void RegisterWtsNotification(HWND hWnd) +// Used to opt-in to receive notification about power events. +// This is mandatory to support Windows 10 Modern Standby and Windows 8.1 Connected Standby power model. +// https://docs.microsoft.com/en-us/windows-hardware/design/device-experiences/prepare-software-for-modern-standby +// https://docs.microsoft.com/en-us/windows/win32/w8cookbook/desktop-activity-moderator?redirectedfrom=MSDN +static HPOWERNOTIFY g_hPowerNotify = NULL; + +static void RegisterWtsAndPowerNotification(HWND hWnd) { if (!hWtsLib) { @@ -203,9 +235,19 @@ static void RegisterWtsNotification(HWND hWnd) } } } + + if (IsOSAtLeast (WIN_8)) + { + REGISTERSUSPENDRESUMENOTIFICATION fnRegisterSuspendResumeNotification = (REGISTERSUSPENDRESUMENOTIFICATION) GetProcAddress (GetModuleHandle (L"user32.dll"), "RegisterSuspendResumeNotification"); + if (fnRegisterSuspendResumeNotification) + { + g_hPowerNotify = fnRegisterSuspendResumeNotification ((HANDLE) hWnd, DEVICE_NOTIFY_WINDOW_HANDLE); + } + + } } -static void UnregisterWtsNotification(HWND hWnd) +static void UnregisterWtsAndPowerNotification(HWND hWnd) { if (hWtsLib && fnWtsUnRegisterSessionNotification) { @@ -215,6 +257,14 @@ static void UnregisterWtsNotification(HWND hWnd) fnWtsRegisterSessionNotification = NULL; fnWtsUnRegisterSessionNotification = NULL; } + + if (IsOSAtLeast (WIN_8) && g_hPowerNotify) + { + UNREGISTERSUSPENDRESUMENOTIFICATION fnUnregisterSuspendResumeNotification = (UNREGISTERSUSPENDRESUMENOTIFICATION) GetProcAddress (GetModuleHandle (L"user32.dll"), "UnregisterSuspendResumeNotification"); + if (fnUnregisterSuspendResumeNotification) + fnUnregisterSuspendResumeNotification (g_hPowerNotify); + g_hPowerNotify = NULL; + } } static std::vector<MSXML2::IXMLDOMNodePtr> GetReadChildNodes (MSXML2::IXMLDOMNodeListPtr childs) @@ -245,7 +295,7 @@ static std::vector<MSXML2::IXMLDOMNodePtr> GetReadChildNodes (MSXML2::IXMLDOMNod static bool validateDcsPropXml(const char* xmlData) { bool bValid = false; - HRESULT hr = CoInitialize(NULL); + HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); if(FAILED(hr)) return false; else @@ -359,12 +409,13 @@ static void localcleanup (void) burn (&CmdVolumePkcs5, sizeof (CmdVolumePkcs5)); burn (&VolumePim, sizeof (VolumePim)); burn (&CmdVolumePim, sizeof (CmdVolumePim)); - burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); - burn (&CmdVolumeTrueCryptMode, sizeof (CmdVolumeTrueCryptMode)); burn (&mountOptions, sizeof (mountOptions)); burn (&defaultMountOptions, sizeof (defaultMountOptions)); burn (szFileName, sizeof(szFileName)); + KeyFileRemoveAll (&FirstCmdKeyFile); + KeyFileRemoveAll (&hidVolProtKeyFilesParam.FirstKeyFile); + /* Cleanup common code resources */ cleanup (); @@ -377,13 +428,71 @@ static void localcleanup (void) RandStop (TRUE); } +#ifndef BS_SPLITBUTTON +#define BS_SPLITBUTTON 0x0000000C +#endif + +#ifndef BCN_DROPDOWN +#define BCN_DROPDOWN (0U-1250U) + 2U +#endif + +static void EnableSplitButton(HWND hwndDlg, int buttonId) +{ + HWND hwndButton = GetDlgItem(hwndDlg, buttonId); + if (hwndButton != NULL) + { + // change the button style + SetWindowLongPtr(hwndButton, GWL_STYLE, GetWindowLongPtr(hwndButton, GWL_STYLE) | BS_SPLITBUTTON); + } +} + +static void DisableSplitButton(HWND hwndDlg, int buttonId) +{ + HWND hwndButton = GetDlgItem(hwndDlg, buttonId); + if (hwndButton != NULL) + { + // change the button style + SetWindowLongPtr(hwndButton, GWL_STYLE, GetWindowLongPtr(hwndButton, GWL_STYLE) & ~BS_SPLITBUTTON); + } +} + +static HMENU CreateMountNoCacheDropdownMenu() +{ + HMENU hmenu = CreatePopupMenu(); + + // add menu items + AppendMenu(hmenu, MF_STRING, IDM_MOUNIT_NO_CACHE, GetString("IDM_MOUNT_NO_CACHE")); + + return hmenu; +} + +static void HandleMountButtonDropdown(HWND hwndButton, HWND hwndOwner, HMENU hmenu) +{ + RECT rc; + POINT pt; + + if (GetClientRect(hwndButton, &rc)) + { + pt.x = rc.left; + pt.y = rc.bottom; + ClientToScreen(hwndButton, &pt); + + TrackPopupMenu(hmenu, TPM_LEFTALIGN | TPM_TOPALIGN, pt.x, pt.y, 0, hwndOwner, NULL); + } +} + void RefreshMainDlg (HWND hwndDlg) { - int drive = (wchar_t) (HIWORD (GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST)))); + if (Silent) + LoadDriveLetters (hwndDlg, NULL, 0); + else + { + int drive = (wchar_t) (HIWORD (GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST)))); - MoveEditToCombo (GetDlgItem (hwndDlg, IDC_VOLUME), bHistory); - LoadDriveLetters (hwndDlg, GetDlgItem (hwndDlg, IDC_DRIVELIST), drive); - EnableDisableButtons (hwndDlg); + MoveEditToCombo (GetDlgItem (hwndDlg, IDC_VOLUME), bHistory); + LoadDriveLetters (hwndDlg, GetDlgItem (hwndDlg, IDC_DRIVELIST), drive); + EnableDisableButtons (hwndDlg); + } } void EndMainDlg (HWND hwndDlg) @@ -415,7 +524,7 @@ void EndMainDlg (HWND hwndDlg) KillTimer (hwndDlg, TIMER_ID_MAIN); KillTimer (hwndDlg, TIMER_ID_UPDATE_DEVICE_LIST); TaskBarIconRemove (hwndDlg); - UnregisterWtsNotification(hwndDlg); + UnregisterWtsAndPowerNotification(hwndDlg); EndDialog (hwndDlg, 0); } } @@ -427,63 +536,66 @@ static void InitMainDialog (HWND hwndDlg) wchar_t *str; int i; - /* Call the common dialog init code */ - InitDialog (hwndDlg); - LocalizeDialog (hwndDlg, NULL); + if (!Silent) + { + /* Call the common dialog init code */ + InitDialog (hwndDlg); + LocalizeDialog (hwndDlg, NULL); - SetWindowLongPtrW (hwndDlg, DWLP_USER, (LONG_PTR) (IsAdmin() ? TC_MAIN_WINDOW_FLAG_ADMIN_PRIVILEGES : 0)); + SetWindowLongPtrW (hwndDlg, DWLP_USER, (LONG_PTR) (IsAdmin() ? TC_MAIN_WINDOW_FLAG_ADMIN_PRIVILEGES : 0)); - DragAcceptFiles (hwndDlg, TRUE); + DragAcceptFiles (hwndDlg, TRUE); - SendMessageW (GetDlgItem (hwndDlg, IDC_VOLUME), CB_LIMITTEXT, TC_MAX_PATH, 0); - SetWindowTextW (hwndDlg, (IsAdmin() && !IsBuiltInAdmin() && IsUacSupported() && !IsNonInstallMode()) ? (wstring (lpszTitle) + L" [" + GetString ("ADMINISTRATOR") + L"]").c_str() : lpszTitle); + SendMessageW (GetDlgItem (hwndDlg, IDC_VOLUME), CB_LIMITTEXT, TC_MAX_PATH, 0); + SetWindowTextW (hwndDlg, (IsAdmin() && !IsBuiltInAdmin() && IsUacSupported() && !IsNonInstallMode()) ? (wstring (lpszTitle) + L" [" + GetString ("ADMINISTRATOR") + L"]").c_str() : lpszTitle); - // Help file name - InitHelpFileName(); + // Help file name + InitHelpFileName(); - // Localize menu strings - for (i = 40001; str = (wchar_t *)GetDictionaryValueByInt (i); i++) - { - info.cbSize = sizeof (info); - info.fMask = MIIM_TYPE; - info.fType = MFT_STRING; - info.dwTypeData = str; - info.cch = (UINT) wcslen (str); + // Localize menu strings + for (i = 40001; str = (wchar_t *)GetDictionaryValueByInt (i); i++) + { + info.cbSize = sizeof (info); + info.fMask = MIIM_TYPE; + info.fType = MFT_STRING; + info.dwTypeData = str; + info.cch = (UINT) wcslen (str); - SetMenuItemInfoW (GetMenu (hwndDlg), i, FALSE, &info); - } + SetMenuItemInfoW (GetMenu (hwndDlg), i, FALSE, &info); + } - for (i = 0; popupTexts[i] != 0; i++) - { - str = GetString (popupTexts[i]); + for (i = 0; popupTexts[i] != 0; i++) + { + str = GetString (popupTexts[i]); - info.cbSize = sizeof (info); - info.fMask = MIIM_TYPE; + info.cbSize = sizeof (info); + info.fMask = MIIM_TYPE; - if (strcmp (popupTexts[i], "MENU_WEBSITE") == 0) - info.fType = MFT_STRING | MFT_RIGHTJUSTIFY; - else - info.fType = MFT_STRING; + if (strcmp (popupTexts[i], "MENU_WEBSITE") == 0) + info.fType = MFT_STRING | MFT_RIGHTJUSTIFY; + else + info.fType = MFT_STRING; - if (strcmp (popupTexts[i], "MENU_FAVORITES") == 0) - FavoriteVolumesMenu = GetSubMenu (GetMenu (hwndDlg), i); + if (strcmp (popupTexts[i], "MENU_FAVORITES") == 0) + FavoriteVolumesMenu = GetSubMenu (GetMenu (hwndDlg), i); - info.dwTypeData = str; - info.cch = (UINT) wcslen (str); + info.dwTypeData = str; + info.cch = (UINT) wcslen (str); - SetMenuItemInfoW (GetMenu (hwndDlg), i, TRUE, &info); - } + SetMenuItemInfoW (GetMenu (hwndDlg), i, TRUE, &info); + } - { - // disable hidden OS creation for GPT system encryption - if (bSystemIsGPT) { - EnableMenuItem (GetMenu (hwndDlg), IDM_CREATE_HIDDEN_OS, MF_GRAYED); + // disable hidden OS creation for GPT system encryption + if (bSystemIsGPT) + { + EnableMenuItem (GetMenu (hwndDlg), IDM_CREATE_HIDDEN_OS, MF_GRAYED); + } } - } - // Disable menu item for changing system header key derivation algorithm until it's implemented - EnableMenuItem (GetMenu (hwndDlg), IDM_CHANGE_SYS_HEADER_KEY_DERIV_ALGO, MF_GRAYED); + // Disable menu item for changing system header key derivation algorithm until it's implemented + EnableMenuItem (GetMenu (hwndDlg), IDM_CHANGE_SYS_HEADER_KEY_DERIV_ALGO, MF_GRAYED); + } try { @@ -494,34 +606,57 @@ static void InitMainDialog (HWND hwndDlg) e.Show (NULL); } - // initialize the list of devices available for mounting as early as possible - UpdateMountableHostDeviceList (); - - // Resize the logo bitmap if the user has a non-default DPI - if (ScreenDPI != USER_DEFAULT_SCREEN_DPI - && hbmLogoBitmapRescaled == NULL) // If not re-called (e.g. after language pack change) + if (NeedPeriodicDeviceListUpdate) { - hbmLogoBitmapRescaled = RenderBitmap (MAKEINTRESOURCE (IDB_LOGO_288DPI), - GetDlgItem (hwndDlg, IDC_LOGO), - 0, 0, 0, 0, FALSE, TRUE); + // initialize the list of devices available for mounting as early as possible + UpdateMountableHostDeviceList (); } - BuildTree (hwndDlg, GetDlgItem (hwndDlg, IDC_DRIVELIST)); - - if (*szDriveLetter != 0) - { - SelectItem (GetDlgItem (hwndDlg, IDC_DRIVELIST), *szDriveLetter); - - if(nSelectedDriveIndex > SendMessage (GetDlgItem (hwndDlg, IDC_DRIVELIST), LVM_GETITEMCOUNT, 0, 0)/2) - SendMessage(GetDlgItem (hwndDlg, IDC_DRIVELIST), LVM_SCROLL, 0, 10000); - } + if (Silent) + LoadDriveLetters (hwndDlg, NULL, 0); else { - SendMessage(hwndDlg, WM_NEXTDLGCTL, (WPARAM) GetDlgItem (hwndDlg, IDC_DRIVELIST), 1L); - } + // Resize the logo bitmap if the user has a non-default DPI + if (ScreenDPI != USER_DEFAULT_SCREEN_DPI + && hbmLogoBitmapRescaled == NULL) // If not re-called (e.g. after language pack change) + { + hbmLogoBitmapRescaled = RenderBitmap (MAKEINTRESOURCE (IDB_LOGO_288DPI), + GetDlgItem (hwndDlg, IDC_LOGO), + 0, 0, 0, 0, FALSE, TRUE); + } - SendMessage (GetDlgItem (hwndDlg, IDC_NO_HISTORY), BM_SETCHECK, bHistory ? BST_UNCHECKED : BST_CHECKED, 0); - EnableDisableButtons (hwndDlg); + BuildTree (hwndDlg, GetDlgItem (hwndDlg, IDC_DRIVELIST)); + + if (*szDriveLetter != 0) + { + SelectItem (GetDlgItem (hwndDlg, IDC_DRIVELIST), *szDriveLetter); + + if(nSelectedDriveIndex > SendMessage (GetDlgItem (hwndDlg, IDC_DRIVELIST), LVM_GETITEMCOUNT, 0, 0)/2) + SendMessage(GetDlgItem (hwndDlg, IDC_DRIVELIST), LVM_SCROLL, 0, 10000); + } + else + { + SendMessage(hwndDlg, WM_NEXTDLGCTL, (WPARAM) GetDlgItem (hwndDlg, IDC_DRIVELIST), 1L); + } + + SendMessage (GetDlgItem (hwndDlg, IDC_NO_HISTORY), BM_SETCHECK, bHistory ? BST_UNCHECKED : BST_CHECKED, 0); + EnableDisableButtons (hwndDlg); + + // Ensure bottom buttons are visible if the user sets a large font size + RECT mainRectScreen, boxRectScreen; + ULONG mainHeigth, mainWidth, correctHeigth; + GetWindowRect (hwndDlg, &mainRectScreen); + GetWindowRect (GetDlgItem (hwndDlg, IDC_LOWER_BOX), &boxRectScreen); + + mainHeigth = mainRectScreen.bottom - mainRectScreen.top; + mainWidth = mainRectScreen.right - mainRectScreen.left; + correctHeigth = boxRectScreen.bottom - mainRectScreen.top + CompensateYDPI (5); + + if (mainHeigth < correctHeigth) + { + SetWindowPos (hwndDlg, NULL, 0, 0, mainWidth, correctHeigth , SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOMOVE); + } + } } void EnableDisableButtons (HWND hwndDlg) @@ -543,7 +678,10 @@ void EnableDisableButtons (HWND hwndDlg) case TC_MLIST_ITEM_NONSYS_VOL: { SetWindowTextW (hOKButton, GetString ("UNMOUNT_BUTTON")); + DisableSplitButton(hwndDlg, IDOK); EnableWindow (hOKButton, TRUE); + // Invalid the button IDOK so that it will be redrawn + InvalidateRect (hOKButton, NULL, TRUE); EnableMenuItem (GetMenu (hwndDlg), IDM_UNMOUNT_VOLUME, MF_ENABLED); EnableWindow (GetDlgItem (hwndDlg, IDC_VOLUME_PROPERTIES), TRUE); @@ -553,15 +691,21 @@ void EnableDisableButtons (HWND hwndDlg) case TC_MLIST_ITEM_SYS_PARTITION: case TC_MLIST_ITEM_SYS_DRIVE: + EnableSplitButton(hwndDlg, IDOK); EnableWindow (hOKButton, FALSE); SetWindowTextW (hOKButton, GetString ("MOUNT_BUTTON")); + // Invalid the button IDOK so that it will be redrawn + InvalidateRect (hOKButton, NULL, TRUE); EnableWindow (GetDlgItem (hwndDlg, IDC_VOLUME_PROPERTIES), TRUE); EnableMenuItem (GetMenu (hwndDlg), IDM_UNMOUNT_VOLUME, MF_GRAYED); break; case TC_MLIST_ITEM_FREE: default: + EnableSplitButton(hwndDlg, IDOK); SetWindowTextW (hOKButton, GetString ("MOUNT_BUTTON")); + // Invalid the button IDOK so that it will be redrawn + InvalidateRect (hOKButton, NULL, TRUE); EnableWindow (GetDlgItem (hwndDlg, IDC_VOLUME_PROPERTIES), FALSE); EnableMenuItem (GetMenu (hwndDlg), IDM_VOLUME_PROPERTIES, MF_GRAYED); EnableMenuItem (GetMenu (hwndDlg), IDM_UNMOUNT_VOLUME, MF_GRAYED); @@ -787,7 +931,10 @@ void LoadSettingsAndCheckModified (HWND hwndDlg, BOOL bOnlyCheckModified, BOOL* { char langid[6] = {0}; if (!bOnlyCheckModified) + { EnableHwEncryption ((ReadDriverConfigurationFlags() & TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION) ? FALSE : TRUE); + EnableCpuRng ((ReadDriverConfigurationFlags() & VC_DRIVER_CONFIG_ENABLE_CPU_RNG) ? TRUE : FALSE); + } WipeAlgorithmId savedWipeAlgorithm = TC_WIPE_NONE; @@ -850,6 +997,8 @@ void LoadSettingsAndCheckModified (HWND hwndDlg, BOOL bOnlyCheckModified, BOOL* ConfigReadCompareInt ("UseSecureDesktop", FALSE, &bUseSecureDesktop, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("UseLegacyMaxPasswordLength", FALSE, &bUseLegacyMaxPasswordLength, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("MountVolumesRemovable", FALSE, &defaultMountOptions.Removable, bOnlyCheckModified, pbSettingsModified); ConfigReadCompareInt ("MountVolumesReadOnly", FALSE, &defaultMountOptions.ReadOnly, bOnlyCheckModified, pbSettingsModified); @@ -861,11 +1010,13 @@ void LoadSettingsAndCheckModified (HWND hwndDlg, BOOL bOnlyCheckModified, BOOL* defaultMountOptions.PartitionInInactiveSysEncScope = FALSE; defaultMountOptions.RecoveryMode = FALSE; defaultMountOptions.UseBackupHeader = FALSE; + defaultMountOptions.SkipCachedPasswords = FALSE; mountOptions = defaultMountOptions; } ConfigReadCompareInt ("CloseSecurityTokenSessionsAfterMount", 0, &CloseSecurityTokenSessionsAfterMount, bOnlyCheckModified, pbSettingsModified); + ConfigReadCompareInt ("EMVSupportEnabled", 0, &EMVSupportEnabled, bOnlyCheckModified, pbSettingsModified); if (IsHiddenOSRunning()) ConfigReadCompareInt ("HiddenSystemLeakProtNotifStatus", TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_NONE, &HiddenSysLeakProtectionNotificationStatus, bOnlyCheckModified, pbSettingsModified); @@ -932,7 +1083,6 @@ void LoadSettingsAndCheckModified (HWND hwndDlg, BOOL bOnlyCheckModified, BOOL* // Mount Options ConfigReadCompareInt ("DefaultPRF", 0, &DefaultVolumePkcs5, bOnlyCheckModified, pbSettingsModified); - ConfigReadCompareInt ("DefaultTrueCryptMode", FALSE, &DefaultVolumeTrueCryptMode, bOnlyCheckModified, pbSettingsModified); if (bOnlyCheckModified) { @@ -956,8 +1106,6 @@ void LoadSettingsAndCheckModified (HWND hwndDlg, BOOL bOnlyCheckModified, BOOL* if (DefaultVolumePkcs5 < 0 || DefaultVolumePkcs5 > LAST_PRF_ID) DefaultVolumePkcs5 = 0; - if (DefaultVolumeTrueCryptMode != TRUE && DefaultVolumeTrueCryptMode != FALSE) - DefaultVolumeTrueCryptMode = FALSE; } @@ -1008,6 +1156,7 @@ void SaveSettings (HWND hwndDlg) ConfigWriteInt ("ShowDisconnectedNetworkDrives",bShowDisconnectedNetworkDrives); ConfigWriteInt ("HideWaitingDialog", bHideWaitingDialog); ConfigWriteInt ("UseSecureDesktop", bUseSecureDesktop); + ConfigWriteInt ("UseLegacyMaxPasswordLength", bUseLegacyMaxPasswordLength); ConfigWriteInt ("EnableBackgroundTask", bEnableBkgTask); ConfigWriteInt ("CloseBackgroundTaskOnNoVolumes", bCloseBkgTaskWhenNoVolumes); @@ -1037,6 +1186,7 @@ void SaveSettings (HWND hwndDlg) } ConfigWriteInt ("CloseSecurityTokenSessionsAfterMount", CloseSecurityTokenSessionsAfterMount); + ConfigWriteInt ("EMVSupportEnabled", EMVSupportEnabled); // Hotkeys ConfigWriteInt ("HotkeyModAutoMountDevices", Hotkeys[HK_AUTOMOUNT_DEVICES].vKeyModifiers); @@ -1068,7 +1218,6 @@ void SaveSettings (HWND hwndDlg) // Mount Options ConfigWriteInt ("DefaultPRF", DefaultVolumePkcs5); - ConfigWriteInt ("DefaultTrueCryptMode", DefaultVolumeTrueCryptMode); ConfigWriteEnd (hwndDlg); } @@ -1492,6 +1641,10 @@ static void LaunchVolCreationWizard (HWND hwndDlg, const wchar_t *arg, BOOL bEle if (!FileExists(t)) Error ("VOL_CREATION_WIZARD_NOT_FOUND", hwndDlg); // Display a user-friendly error message and advise what to do + else if (!VerifyModuleSignature (t)) + { + Error ("DIST_PACKAGE_CORRUPTED", hwndDlg); + } else { @@ -1564,7 +1717,7 @@ static void LaunchVolExpander (HWND hwndDlg) void LoadDriveLetters (HWND hwndDlg, HWND hTree, int drive) { // Remember the top-most visible item - int lastTopMostVisibleItem = ListView_GetTopIndex (hTree); + int lastTopMostVisibleItem = (!Silent && hTree)? ListView_GetTopIndex (hTree) : 0; wchar_t *szDriveLetters[]= {L"A:", L"B:", L"C:", L"D:", @@ -1618,6 +1771,9 @@ void LoadDriveLetters (HWND hwndDlg, HWND hTree, int drive) if (dwUsedDrives == 0) Warning ("DRIVELETTERS", hwndDlg); + if (Silent) + return; + if(drive == 0) ListView_DeleteAllItems(hTree); @@ -1711,7 +1867,7 @@ void LoadDriveLetters (HWND hwndDlg, HWND hTree, int drive) if (propSysEnc.ea >= EAGetFirst() && propSysEnc.ea <= EAGetCount()) { - EAGetName (szTmp, propSysEnc.ea, 1); + EAGetName (szTmp, ARRAYSIZE(szTmp),propSysEnc.ea, 1); } else { @@ -1837,7 +1993,7 @@ void LoadDriveLetters (HWND hwndDlg, HWND hTree, int drive) GetSizeString (bSysEncPartition ? GetSysEncDeviceSize(TRUE) : driver.diskLength[i], szTmpW, sizeof(szTmpW)); ListSubItemSet (hTree, listItem.iItem, 2, szTmpW); - EAGetName (szTmp, bSysEncPartition ? propSysEnc.ea : driver.ea[i], 1); + EAGetName (szTmp, ARRAYSIZE(szTmp),bSysEncPartition ? propSysEnc.ea : driver.ea[i], 1); listItem.iSubItem = 3; ListView_SetItem (hTree, &listItem); @@ -1867,13 +2023,7 @@ void LoadDriveLetters (HWND hwndDlg, HWND hTree, int drive) ws = L"?"; } - if (driver.truecryptMode[i]) - { - StringCbPrintfW (szTmpW, sizeof(szTmpW), L"TrueCrypt-%s", ws); - ListSubItemSet (hTree, listItem.iItem, 4, szTmpW); - } - else - ListSubItemSet (hTree, listItem.iItem, 4, ws); + ListSubItemSet (hTree, listItem.iItem, 4, ws); if (driver.volumeType[i] == PROP_VOL_TYPE_OUTER_VOL_WRITE_PREVENTED) // Normal/outer volume (hidden volume protected AND write denied) { @@ -2000,7 +2150,6 @@ typedef struct int pkcs5; int pim; int wipePassCount; - BOOL truecryptMode; int* pnStatus; } ChangePwdThreadParam; @@ -2037,14 +2186,14 @@ void CALLBACK ChangePwdWaitThreadProc(void* pArg, HWND hwndDlg) { // Non-system - *pThreadParam->pnStatus = ChangePwd (szFileName, pThreadParam->oldPassword, pThreadParam->old_pkcs5, pThreadParam->old_pim, pThreadParam->truecryptMode, pThreadParam->newPassword, pThreadParam->pkcs5, pThreadParam->pim, pThreadParam->wipePassCount, hwndDlg); + *pThreadParam->pnStatus = ChangePwd (szFileName, pThreadParam->oldPassword, pThreadParam->old_pkcs5, pThreadParam->old_pim, pThreadParam->newPassword, pThreadParam->pkcs5, pThreadParam->pim, pThreadParam->wipePassCount, hwndDlg); if (*pThreadParam->pnStatus == ERR_OS_ERROR && GetLastError () == ERROR_ACCESS_DENIED && IsUacSupported () && IsVolumeDeviceHosted (szFileName)) { - *pThreadParam->pnStatus = UacChangePwd (szFileName, pThreadParam->oldPassword, pThreadParam->old_pkcs5, pThreadParam->old_pim, pThreadParam->truecryptMode, pThreadParam->newPassword, pThreadParam->pkcs5, pThreadParam->pim, pThreadParam->wipePassCount, hwndDlg); + *pThreadParam->pnStatus = UacChangePwd (szFileName, pThreadParam->oldPassword, pThreadParam->old_pkcs5, pThreadParam->old_pim, pThreadParam->newPassword, pThreadParam->pkcs5, pThreadParam->pim, pThreadParam->wipePassCount, hwndDlg); } } } @@ -2119,7 +2268,6 @@ BOOL CALLBACK PasswordChangeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPAR int i; WipeAlgorithmId headerWipeMode = TC_WIPE_3_DOD_5220; int EffectiveVolumePkcs5 = CmdVolumePkcs5; - BOOL EffectiveVolumeTrueCryptMode = CmdVolumeTrueCryptMode; int EffectiveVolumePim = CmdVolumePim; /* Priority is given to command line parameters @@ -2127,8 +2275,6 @@ BOOL CALLBACK PasswordChangeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPAR */ if (EffectiveVolumePkcs5 == 0) EffectiveVolumePkcs5 = DefaultVolumePkcs5; - if (!EffectiveVolumeTrueCryptMode) - EffectiveVolumeTrueCryptMode = DefaultVolumeTrueCryptMode; NewPimValuePtr = (int*) lParam; @@ -2146,9 +2292,9 @@ BOOL CALLBACK PasswordChangeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPAR SetWindowTextW (hwndDlg, GetString ("IDD_PASSWORDCHANGE_DLG")); LocalizeDialog (hwndDlg, "IDD_PASSWORDCHANGE_DLG"); - SendMessage (GetDlgItem (hwndDlg, IDC_OLD_PASSWORD), EM_LIMITTEXT, MAX_PASSWORD, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_PASSWORD), EM_LIMITTEXT, MAX_PASSWORD, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_VERIFY), EM_LIMITTEXT, MAX_PASSWORD, 0); + ToNormalPwdField (hwndDlg, IDC_OLD_PASSWORD); + ToNormalPwdField (hwndDlg, IDC_PASSWORD); + ToNormalPwdField (hwndDlg, IDC_VERIFY); SendMessage (GetDlgItem (hwndDlg, IDC_OLD_PIM), EM_LIMITTEXT, MAX_PIM, 0); SendMessage (GetDlgItem (hwndDlg, IDC_PIM), EM_LIMITTEXT, MAX_PIM, 0); EnableWindow (GetDlgItem (hwndDlg, IDOK), FALSE); @@ -2175,9 +2321,6 @@ BOOL CALLBACK PasswordChangeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPAR SendMessage (hComboBox, CB_SETCURSEL, nSelectedIndex, 0); - /* check TrueCrypt Mode if it was set as default*/ - SetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE, EffectiveVolumeTrueCryptMode); - /* set default PIM if set in the command line*/ if (EffectiveVolumePim > 0) { @@ -2276,10 +2419,6 @@ BOOL CALLBACK PasswordChangeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPAR if (bSysEncPwdChangeDlgMode) { - /* No support for changing the password of TrueCrypt system partition */ - SetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE, FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_TRUECRYPT_MODE), FALSE); - ToBootPwdField (hwndDlg, IDC_PASSWORD); ToBootPwdField (hwndDlg, IDC_VERIFY); ToBootPwdField (hwndDlg, IDC_OLD_PASSWORD); @@ -2320,6 +2459,17 @@ BOOL CALLBACK PasswordChangeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPAR } CheckCapsLock (hwndDlg, FALSE); + + if (!bSecureDesktopOngoing) + { + PasswordEditDropTarget* pTarget = new PasswordEditDropTarget (); + if (pTarget->Register (hwndDlg)) + { + SetWindowLongPtr (hwndDlg, DWLP_USER, (LONG_PTR) pTarget); + } + else + delete pTarget; + } return 0; } @@ -2596,14 +2746,6 @@ BOOL CALLBACK PasswordChangeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPAR } - if (lw == IDC_TRUECRYPT_MODE) - { - BOOL bEnablePim = GetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE) ? FALSE: TRUE; - EnableWindow (GetDlgItem (hwndDlg, IDT_OLD_PIM), bEnablePim); - EnableWindow (GetDlgItem (hwndDlg, IDC_OLD_PIM), bEnablePim); - EnableWindow (GetDlgItem (hwndDlg, IDC_OLD_PIM_HELP), bEnablePim); - } - if (lw == IDC_SHOW_PASSWORD_CHPWD_ORI) { HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PASSWORD_CHPWD_ORI, IDC_OLD_PASSWORD, IDC_OLD_PIM); @@ -2632,21 +2774,10 @@ BOOL CALLBACK PasswordChangeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPAR SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_OLD_PRF_ID), CB_GETCURSEL, 0, 0), 0); int pkcs5 = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETITEMDATA, SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETCURSEL, 0, 0), 0); - BOOL truecryptMode = GetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE); int old_pim = GetPim (hwndDlg, IDC_OLD_PIM, 0); int pim = GetPim (hwndDlg, IDC_PIM, 0); - - if (truecryptMode && !is_pkcs5_prf_supported (old_pkcs5, TRUE, PRF_BOOT_NO)) - { - Error ("ALGO_NOT_SUPPORTED_FOR_TRUECRYPT_MODE", hwndDlg); - return 1; - } - else if (truecryptMode && (old_pim != 0)) - { - Error ("PIM_NOT_SUPPORTED_FOR_TRUECRYPT_MODE", hwndDlg); - return 1; - } + int iMaxPasswordLength = (bUseLegacyMaxPasswordLength)? MAX_LEGACY_PASSWORD : MAX_PASSWORD; if (bSysEncPwdChangeDlgMode && !CheckPasswordCharEncoding (GetDlgItem (hwndDlg, IDC_PASSWORD), NULL)) { @@ -2693,7 +2824,7 @@ BOOL CALLBACK PasswordChangeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPAR GetVolumePath (hParent, szFileName, ARRAYSIZE (szFileName)); - if (GetPassword (hwndDlg, IDC_OLD_PASSWORD, (LPSTR) oldPassword.Text, sizeof (oldPassword.Text), TRUE)) + if (GetPassword (hwndDlg, IDC_OLD_PASSWORD, (LPSTR) oldPassword.Text, iMaxPasswordLength + 1, FALSE, TRUE)) oldPassword.Length = (unsigned __int32) strlen ((char *) oldPassword.Text); else { @@ -2711,7 +2842,7 @@ BOOL CALLBACK PasswordChangeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPAR break; default: - if (GetPassword (hwndDlg, IDC_PASSWORD, (LPSTR) newPassword.Text, sizeof (newPassword.Text), TRUE)) + if (GetPassword (hwndDlg, IDC_PASSWORD, (LPSTR) newPassword.Text, iMaxPasswordLength + 1, FALSE, TRUE)) newPassword.Length = (unsigned __int32) strlen ((char *) newPassword.Text); else return 1; @@ -2740,7 +2871,6 @@ BOOL CALLBACK PasswordChangeDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPAR changePwdParam.pim = pim; changePwdParam.wipePassCount = GetWipePassCount(headerWiperMode); changePwdParam.pnStatus = &nStatus; - changePwdParam.truecryptMode = truecryptMode; ShowWaitDialog(hwndDlg, TRUE, ChangePwdWaitThreadProc, &changePwdParam); @@ -2784,6 +2914,19 @@ err: return 1; } return 0; + + case WM_NCDESTROY: + { + /* unregister drap-n-drop support */ + PasswordEditDropTarget* pTarget = (PasswordEditDropTarget*) GetWindowLongPtr (hwndDlg, DWLP_USER); + if (pTarget) + { + SetWindowLongPtr (hwndDlg, DWLP_USER, (LONG_PTR) 0); + pTarget->Revoke (); + pTarget->Release(); + } + } + return 0; } return 0; @@ -2802,7 +2945,6 @@ BOOL CALLBACK PasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa static Password *szXPwd; static int *pkcs5; static int *pim; - static BOOL* truecryptMode; switch (msg) { @@ -2812,7 +2954,6 @@ BOOL CALLBACK PasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa szXPwd = ((PasswordDlgParam *) lParam) -> password; pkcs5 = ((PasswordDlgParam *) lParam) -> pkcs5; pim = ((PasswordDlgParam *) lParam) -> pim; - truecryptMode = ((PasswordDlgParam *) lParam) -> truecryptMode; LocalizeDialog (hwndDlg, "IDD_PASSWORD_DLG"); DragAcceptFiles (hwndDlg, TRUE); @@ -2861,7 +3002,7 @@ BOOL CALLBACK PasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa /* make autodetection the default unless a specific PRF was specified in the command line */ SendMessage (hComboBox, CB_SETCURSEL, defaultPrfIndex, 0); - SendMessage (GetDlgItem (hwndDlg, IDC_PASSWORD), EM_LIMITTEXT, MAX_PASSWORD, 0); + ToNormalPwdField (hwndDlg, IDC_PASSWORD); SendMessage (GetDlgItem (hwndDlg, IDC_CACHE), BM_SETCHECK, bCacheInDriver ? BST_CHECKED:BST_UNCHECKED, 0); SendMessage (GetDlgItem (hwndDlg, IDC_PIM), EM_LIMITTEXT, MAX_PIM, 0); @@ -2890,14 +3031,6 @@ BOOL CALLBACK PasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa { EnableWindow (GetDlgItem (hwndDlg, IDC_CACHE), FALSE); EnableWindow (GetDlgItem (hwndDlg, IDC_MOUNT_OPTIONS), FALSE); - /* Disable TrueCrypt mode option in case of backup/restore header operation */ - SetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE, FALSE); - EnableWindow (GetDlgItem (hwndDlg, IDC_TRUECRYPT_MODE), FALSE); - } - else if (*truecryptMode) - { - /* Check TrueCryptMode if it is enabled on the command line */ - SetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE, TRUE); } if (!SetForegroundWindow (hwndDlg) && (FavoriteMountOnArrivalInProgress || LogOn)) @@ -2915,6 +3048,22 @@ BOOL CALLBACK PasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa SetWindowPos (hwndDlg, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); } + SetFocus (GetDlgItem (hwndDlg, IDC_PASSWORD)); + + /* Start the timer to check if we are foreground only if Secure Desktop is not used */ + /* Implement Text drag-n-drop in order to support droping password from KeePass directly only if Secure Desktop is not used */ + if (!bSecureDesktopOngoing) + { + SetTimer (hwndDlg, TIMER_ID_CHECK_FOREGROUND, TIMER_INTERVAL_CHECK_FOREGROUND, NULL); + + PasswordEditDropTarget* pTarget = new PasswordEditDropTarget (); + if (pTarget->Register (hwndDlg)) + { + SetWindowLongPtr (hwndDlg, DWLP_USER, (LONG_PTR) pTarget); + } + else + delete pTarget; + } } return 0; @@ -2957,11 +3106,16 @@ BOOL CALLBACK PasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa if (keybLayout != 0x00000409 && keybLayout != 0x04090409) { Error ("CANT_CHANGE_KEYB_LAYOUT_FOR_SYS_ENCRYPTION", hwndDlg); - EndDialog (hwndDlg, IDCANCEL); - return 1; + /* don't be too agressive on enforcing an English keyboard layout. E.g. on WindowsPE this call fails and + * then the user can only mount a system encrypted device using the command line by passing the password as a parameter + * (which might not be obvious for not so advanced users). + * + * Now, we informed the user that English keyboard is required, if it is not available the volume can just not be mounted. + * There should be no other drawback (as e.g., on the change password dialog, when you might change to a password which won't + * work on the pre-start environment. + */ } - - if (SetTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD, TIMER_INTERVAL_KEYB_LAYOUT_GUARD, NULL) == 0) + else if (SetTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD, TIMER_INTERVAL_KEYB_LAYOUT_GUARD, NULL) == 0) { Error ("CANNOT_SET_TIMER", hwndDlg); EndDialog (hwndDlg, IDCANCEL); @@ -2989,6 +3143,17 @@ BOOL CALLBACK PasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa case WM_TIMER: switch (wParam) { + case TIMER_ID_CHECK_FOREGROUND: + if (hwndDlg != ::GetForegroundWindow ()) + { + // we are not foreground after 500ms of creating the dialog + // try to force it for be foreground + BringToForeground (hwndDlg); + SetFocus (GetDlgItem (hwndDlg, IDC_PASSWORD)); + } + // one shot timer: stop it + KillTimer (hwndDlg, TIMER_ID_CHECK_FOREGROUND); + return 0; case TIMER_ID_KEYB_LAYOUT_GUARD: if (bPrebootPasswordDlgMode) { @@ -3062,14 +3227,6 @@ BOOL CALLBACK PasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa return 1; } - if (lw == IDC_TRUECRYPT_MODE) - { - BOOL bEnablePim = GetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE) ? FALSE: TRUE; - EnableWindow (GetDlgItem (hwndDlg, IDT_PIM), bEnablePim); - EnableWindow (GetDlgItem (hwndDlg, IDC_PIM), bEnablePim); - EnableWindow (GetDlgItem (hwndDlg, IDC_PIM_HELP), bEnablePim); - } - if (lw == IDC_KEY_FILES) { KeyFilesDlgParam param; @@ -3102,36 +3259,19 @@ BOOL CALLBACK PasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa if (lw == IDOK) { + int iMaxPasswordLength = (bUseLegacyMaxPasswordLength)? MAX_LEGACY_PASSWORD : MAX_PASSWORD; if (mountOptions.ProtectHiddenVolume && hidVolProtKeyFilesParam.EnableKeyFiles) KeyFilesApply (hwndDlg, &mountOptions.ProtectedHidVolPassword, hidVolProtKeyFilesParam.FirstKeyFile, wcslen (PasswordDlgVolume) > 0 ? PasswordDlgVolume : NULL); - if (GetPassword (hwndDlg, IDC_PASSWORD, (LPSTR) szXPwd->Text, MAX_PASSWORD + 1, TRUE)) + if (GetPassword (hwndDlg, IDC_PASSWORD, (LPSTR) szXPwd->Text, iMaxPasswordLength + 1, FALSE, TRUE)) szXPwd->Length = (unsigned __int32) strlen ((char *) szXPwd->Text); else return 1; bCacheInDriver = IsButtonChecked (GetDlgItem (hwndDlg, IDC_CACHE)); *pkcs5 = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETITEMDATA, SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETCURSEL, 0, 0), 0); - *truecryptMode = GetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE); *pim = GetPim (hwndDlg, IDC_PIM, 0); - - /* check that PRF is supported in TrueCrypt Mode */ - if ( (*truecryptMode) - && ((!is_pkcs5_prf_supported (*pkcs5, TRUE, PRF_BOOT_NO)) || (mountOptions.ProtectHiddenVolume && !is_pkcs5_prf_supported (mountOptions.ProtectedHidVolPkcs5Prf, TRUE, PRF_BOOT_NO))) - ) - { - Error ("ALGO_NOT_SUPPORTED_FOR_TRUECRYPT_MODE", hwndDlg); - return 1; - } - - if ( (*truecryptMode) - && (*pim != 0) - ) - { - Error ("PIM_NOT_SUPPORTED_FOR_TRUECRYPT_MODE", hwndDlg); - return 1; - } } // Attempt to wipe password stored in the input field buffer @@ -3160,6 +3300,19 @@ BOOL CALLBACK PasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa } return 0; + case WM_NCDESTROY: + { + /* unregister drap-n-drop support */ + PasswordEditDropTarget* pTarget = (PasswordEditDropTarget*) GetWindowLongPtr (hwndDlg, DWLP_USER); + if (pTarget) + { + SetWindowLongPtr (hwndDlg, DWLP_USER, (LONG_PTR) 0); + pTarget->Revoke (); + pTarget->Release(); + } + } + return 0; + case WM_CONTEXTMENU: { RECT buttonRect; @@ -3278,6 +3431,9 @@ BOOL CALLBACK PreferencesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM SendMessage (GetDlgItem (hwndDlg, IDC_SECURE_DESKTOP_PASSWORD_ENTRY), BM_SETCHECK, bUseSecureDesktop ? BST_CHECKED:BST_UNCHECKED, 0); + SendMessage (GetDlgItem (hwndDlg, IDC_USE_LEGACY_MAX_PASSWORD_LENGTH), BM_SETCHECK, + bUseLegacyMaxPasswordLength ? BST_CHECKED:BST_UNCHECKED, 0); + SendMessage (GetDlgItem (hwndDlg, IDC_PREF_TEMP_CACHE_ON_MULTIPLE_MOUNT), BM_SETCHECK, bCacheDuringMultipleMount ? BST_CHECKED:BST_UNCHECKED, 0); @@ -3394,6 +3550,7 @@ BOOL CALLBACK PreferencesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM bShowDisconnectedNetworkDrives = IsButtonChecked (GetDlgItem (hwndDlg, IDC_SHOW_DISCONNECTED_NETWORK_DRIVES)); bHideWaitingDialog = IsButtonChecked (GetDlgItem (hwndDlg, IDC_HIDE_WAITING_DIALOG)); bUseSecureDesktop = IsButtonChecked (GetDlgItem (hwndDlg, IDC_SECURE_DESKTOP_PASSWORD_ENTRY)); + bUseLegacyMaxPasswordLength = IsButtonChecked (GetDlgItem (hwndDlg, IDC_USE_LEGACY_MAX_PASSWORD_LENGTH)); bCacheDuringMultipleMount = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_TEMP_CACHE_ON_MULTIPLE_MOUNT)); bWipeCacheOnExit = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_WIPE_CACHE_ON_EXIT)); bWipeCacheOnAutoDismount = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PREF_WIPE_CACHE_ON_AUTODISMOUNT)); @@ -3484,8 +3641,8 @@ BOOL CALLBACK MountOptionsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM mountOptions->ReadOnly ? BST_CHECKED : BST_UNCHECKED, 0); SendDlgItemMessage (hwndDlg, IDC_MOUNT_REMOVABLE, BM_SETCHECK, mountOptions->Removable ? BST_CHECKED : BST_UNCHECKED, 0); - SendDlgItemMessage (hwndDlg, IDC_PROTECT_HIDDEN_VOL, BM_SETCHECK, - mountOptions->ProtectHiddenVolume ? BST_CHECKED : BST_UNCHECKED, 0); + SendDlgItemMessage (hwndDlg, IDC_DISABLE_MOUNT_MANAGER, BM_SETCHECK, + mountOptions->DisableMountManager ? BST_CHECKED : BST_UNCHECKED, 0); SendDlgItemMessage (hwndDlg, IDC_PROTECT_HIDDEN_VOL, BM_SETCHECK, mountOptions->ProtectHiddenVolume ? BST_CHECKED : BST_UNCHECKED, 0); @@ -3503,6 +3660,10 @@ BOOL CALLBACK MountOptionsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM SetDlgItemTextW (hwndDlg, IDC_VOLUME_LABEL, mountOptions->Label); SendDlgItemMessage (hwndDlg, IDC_VOLUME_LABEL, EM_LIMITTEXT, 32, 0); // 32 is the maximum possible length for a drive label in Windows + protect = IsButtonChecked (GetDlgItem (hwndDlg, IDC_DISABLE_MOUNT_MANAGER)); + EnableWindow (GetDlgItem (hwndDlg, IDC_VOLUME_LABEL), !protect); + EnableWindow (GetDlgItem (hwndDlg, IDT_VOLUME_LABEL), !protect); + /* Add PRF algorithm list for hidden volume password */ HWND hComboBox = GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID); SendMessage (hComboBox, CB_RESETCONTENT, 0, 0); @@ -3539,7 +3700,7 @@ BOOL CALLBACK MountOptionsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE_HIDVOL_PROT, hidVolProtKeyFilesParam.EnableKeyFiles); - SendDlgItemMessage (hwndDlg, IDC_PASSWORD_PROT_HIDVOL, EM_LIMITTEXT, MAX_PASSWORD, 0); + ToNormalPwdField (hwndDlg, IDC_PASSWORD_PROT_HIDVOL); SendDlgItemMessage (hwndDlg, IDC_PIM, EM_LIMITTEXT, MAX_PIM, 0); if (mountOptions->ProtectedHidVolPassword.Length > 0) @@ -3565,6 +3726,17 @@ BOOL CALLBACK MountOptionsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM ToHyperlink (hwndDlg, IDC_LINK_HIDVOL_PROTECTION_INFO); + if (!bSecureDesktopOngoing) + { + PasswordEditDropTarget* pTarget = new PasswordEditDropTarget (); + if (pTarget->Register (hwndDlg)) + { + SetWindowLongPtr (hwndDlg, DWLP_USER, (LONG_PTR) pTarget); + } + else + delete pTarget; + } + } return 0; @@ -3649,6 +3821,7 @@ BOOL CALLBACK MountOptionsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM mountOptions->ReadOnly = IsButtonChecked (GetDlgItem (hwndDlg, IDC_MOUNT_READONLY)); mountOptions->Removable = IsButtonChecked (GetDlgItem (hwndDlg, IDC_MOUNT_REMOVABLE)); + mountOptions->DisableMountManager = IsButtonChecked (GetDlgItem (hwndDlg, IDC_DISABLE_MOUNT_MANAGER)); mountOptions->ProtectHiddenVolume = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PROTECT_HIDDEN_VOL)); mountOptions->PartitionInInactiveSysEncScope = IsButtonChecked (GetDlgItem (hwndDlg, IDC_MOUNT_SYSENC_PART_WITHOUT_PBA)); mountOptions->UseBackupHeader = IsButtonChecked (GetDlgItem (hwndDlg, IDC_USE_EMBEDDED_HEADER_BAK)); @@ -3657,9 +3830,10 @@ BOOL CALLBACK MountOptionsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM if (mountOptions->ProtectHiddenVolume) { + int iMaxPasswordLength = bUseLegacyMaxPasswordLength? MAX_LEGACY_PASSWORD : MAX_PASSWORD; GetPassword (hwndDlg, IDC_PASSWORD_PROT_HIDVOL, - (LPSTR) mountOptions->ProtectedHidVolPassword.Text, MAX_PASSWORD + 1, - FALSE); + (LPSTR) mountOptions->ProtectedHidVolPassword.Text, iMaxPasswordLength + 1, + FALSE, FALSE); mountOptions->ProtectedHidVolPassword.Length = (unsigned __int32) strlen ((char *) mountOptions->ProtectedHidVolPassword.Text); @@ -3685,7 +3859,7 @@ BOOL CALLBACK MountOptionsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM return 1; } - if (lw == IDC_MOUNT_READONLY || lw == IDC_PROTECT_HIDDEN_VOL) + if (lw == IDC_MOUNT_READONLY || lw == IDC_PROTECT_HIDDEN_VOL || lw == IDC_DISABLE_MOUNT_MANAGER) { BOOL protect; @@ -3696,6 +3870,12 @@ BOOL CALLBACK MountOptionsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM EnableWindow (GetDlgItem (hwndDlg, IDT_HIDDEN_VOL_PROTECTION), !IsButtonChecked (GetDlgItem (hwndDlg, IDC_MOUNT_READONLY))); } + if (lw == IDC_DISABLE_MOUNT_MANAGER) + { + EnableWindow (GetDlgItem (hwndDlg, IDC_VOLUME_LABEL), !IsButtonChecked (GetDlgItem (hwndDlg, IDC_DISABLE_MOUNT_MANAGER))); + EnableWindow (GetDlgItem (hwndDlg, IDT_VOLUME_LABEL), !IsButtonChecked (GetDlgItem (hwndDlg, IDC_DISABLE_MOUNT_MANAGER))); + } + protect = IsButtonChecked (GetDlgItem (hwndDlg, IDC_PROTECT_HIDDEN_VOL)); EnableWindow (GetDlgItem (hwndDlg, IDC_PASSWORD_PROT_HIDVOL), protect); @@ -3714,6 +3894,19 @@ BOOL CALLBACK MountOptionsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM } return 0; + + case WM_NCDESTROY: + { + /* unregister drap-n-drop support */ + PasswordEditDropTarget* pTarget = (PasswordEditDropTarget*) GetWindowLongPtr (hwndDlg, DWLP_USER); + if (pTarget) + { + SetWindowLongPtr (hwndDlg, DWLP_USER, (LONG_PTR) 0); + pTarget->Revoke (); + pTarget->Release(); + } + } + return 0; } return 0; @@ -3949,6 +4142,14 @@ BOOL CALLBACK VolumePropertiesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LP else ListSubItemSet (list, i++, 1, (wchar_t *) (prop.wszVolume[1] != L'?' ? prop.wszVolume : prop.wszVolume + 4)); + if (!bSysEnc && prop.mountDisabled) + { + // Virtual Device + StringCbPrintfW (szTmp, sizeof(szTmp), L"\\Device\\VeraCryptVolume%c", (wchar_t) prop.driveNo + L'A'); + ListItemAdd (list, i, GetString ("VIRTUAL_DEVICE")); + ListSubItemSet (list, i++, 1, szTmp); + } + if (!bSysEnc && IsVolumeDeviceHosted ((wchar_t *) (prop.wszVolume[1] != L'?' ? prop.wszVolume : prop.wszVolume + 4))) { // Volume ID @@ -3970,17 +4171,10 @@ BOOL CALLBACK VolumePropertiesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LP ListSubItemSet (list, i++, 1, GetString (IsHiddenOSRunning() ? "TYPE_HIDDEN_SYSTEM_ADJECTIVE" : "SYSTEM_VOLUME_TYPE_ADJECTIVE")); else { - bool truecryptMode = prop.pkcs5Iterations == get_pkcs5_iteration_count(prop.pkcs5, 0, TRUE, prop.partitionInInactiveSysEncScope); s = prop.hiddenVolume ? GetString ("HIDDEN") : (prop.hiddenVolProtection != HIDVOL_PROT_STATUS_NONE ? GetString ("OUTER") : GetString ("NORMAL")); - if (truecryptMode) - { - StringCbPrintfW (sw, sizeof(sw), L"TrueCrypt - %s", s); - ListSubItemSet (list, i++, 1, sw); - } - else - ListSubItemSet (list, i++, 1, s); + ListSubItemSet (list, i++, 1, s); } if (!bSysEnc) @@ -4018,14 +4212,14 @@ BOOL CALLBACK VolumePropertiesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LP return 1; } - EAGetName (szTmp, prop.ea, 1); + EAGetName (szTmp, ARRAYSIZE(szTmp), prop.ea, 1); ListSubItemSet (list, i++, 1, szTmp); // Key size(s) { wchar_t name[128]; int size = EAGetKeySize (prop.ea); - EAGetName (name, prop.ea, 1); + EAGetName (name, ARRAYSIZE(name), prop.ea, 1); // Primary key ListItemAdd (list, i, GetString ("KEY_SIZE")); @@ -4086,7 +4280,7 @@ BOOL CALLBACK VolumePropertiesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LP GetDateFormatW (LOCALE_USER_DEFAULT, 0, &st, 0, sw, sizeof (sw)/2); swprintf (date, L"%s ", sw); GetTimeFormatW (LOCALE_USER_DEFAULT, 0, &st, 0, sw, sizeof (sw)/2); - wcscat (date, sw); + StringCchCatW (date, ARRAYSIZE(date), sw); ListSubItemSet (list, i++, 1, date); // Header date @@ -4096,7 +4290,7 @@ BOOL CALLBACK VolumePropertiesDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LP GetDateFormatW (LOCALE_USER_DEFAULT, 0, &st, 0, sw, sizeof (sw)/2); swprintf (date, L"%s ", sw); GetTimeFormatW (LOCALE_USER_DEFAULT, 0, &st, 0, sw, sizeof (sw)/2); - wcscat (date, sw); + StringCchCatW (date, ARRAYSIZE(date), sw); GetLocalTime (&st); SystemTimeToFileTime (&st, &curFt); @@ -4320,7 +4514,7 @@ BOOL CALLBACK TravelerDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa wchar_t dstPath[MAX_PATH * 2]; GetDlgItemText (hwndDlg, IDC_DIRECTORY, dstPath, ARRAYSIZE (dstPath)); - if (BrowseDirectories (hwndDlg, "SELECT_DEST_DIR", dstPath)) + if (BrowseDirectories (hwndDlg, "SELECT_DEST_DIR", dstPath, dstPath)) SetDlgItemText (hwndDlg, IDC_DIRECTORY, dstPath); return 1; @@ -4394,102 +4588,341 @@ BOOL CALLBACK TravelerDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa goto stop; } - // Main app 32-bit - if (Is64BitOs () && !IsNonInstallMode ()) - StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt-x86.exe", appDir); - else - StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt.exe", appDir); - StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCrypt.exe", dstDir); - if (!TCCopyFile (srcPath, dstPath)) + if (IsNonInstallMode ()) { - handleWin32Error (hwndDlg, SRC_POS); - goto stop; - } - - // Main app 64-bit - if (Is64BitOs () && !IsNonInstallMode ()) + // Main app 32-bit StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt.exe", appDir); - else - StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt-x64.exe", appDir); - StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCrypt-x64.exe", dstDir); - if (!TCCopyFile (srcPath, dstPath)) - { - handleWin32Error (hwndDlg, SRC_POS); - goto stop; - } + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCrypt.exe", dstDir); + if (!VerifyModuleSignature (srcPath)) + { + Error ("DIST_PACKAGE_CORRUPTED", hwndDlg); + goto stop; + } + else if (!TCCopyFile (srcPath, dstPath)) + { + handleWin32Error (hwndDlg, SRC_POS); + goto stop; + } - // Wizard - if (copyWizard) - { - // Wizard 32-bit - if (Is64BitOs () && !IsNonInstallMode ()) - StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt Format-x86.exe", appDir); - else - StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt Format.exe", appDir); - StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCrypt Format.exe", dstDir); - if (!TCCopyFile (srcPath, dstPath)) + // Main app 64-bit + StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt-x64.exe", appDir); + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCrypt-x64.exe", dstDir); + if (!VerifyModuleSignature (srcPath)) + { + Error ("DIST_PACKAGE_CORRUPTED", hwndDlg); + goto stop; + } + else if (!TCCopyFile (srcPath, dstPath)) { handleWin32Error (hwndDlg, SRC_POS); goto stop; } - // Wizard 64-bit - if (Is64BitOs () && !IsNonInstallMode ()) + // Main app ARM 64-bit + StringCbPrintfW(srcPath, sizeof(srcPath), L"%s\\VeraCrypt-arm64.exe", appDir); + StringCbPrintfW(dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCrypt-arm64.exe", dstDir); + if (!VerifyModuleSignature(srcPath)) + { + Error("DIST_PACKAGE_CORRUPTED", hwndDlg); + goto stop; + } + else if (!TCCopyFile(srcPath, dstPath)) + { + handleWin32Error(hwndDlg, SRC_POS); + goto stop; + } + + // Wizard + if (copyWizard) + { + // Wizard 32-bit StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt Format.exe", appDir); - else + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCrypt Format.exe", dstDir); + if (!VerifyModuleSignature (srcPath)) + { + Error ("DIST_PACKAGE_CORRUPTED", hwndDlg); + goto stop; + } + else if (!TCCopyFile (srcPath, dstPath)) + { + handleWin32Error (hwndDlg, SRC_POS); + goto stop; + } + + // Wizard 64-bit StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt Format-x64.exe", appDir); - StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCrypt Format-x64.exe", dstDir); - if (!TCCopyFile (srcPath, dstPath)) + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCrypt Format-x64.exe", dstDir); + if (!VerifyModuleSignature (srcPath)) + { + Error ("DIST_PACKAGE_CORRUPTED", hwndDlg); + goto stop; + } + else if (!TCCopyFile (srcPath, dstPath)) + { + handleWin32Error (hwndDlg, SRC_POS); + goto stop; + } + + // Wizard ARM 64-bit + StringCbPrintfW(srcPath, sizeof(srcPath), L"%s\\VeraCrypt Format-arm64.exe", appDir); + StringCbPrintfW(dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCrypt Format-arm64.exe", dstDir); + if (!VerifyModuleSignature(srcPath)) + { + Error("DIST_PACKAGE_CORRUPTED", hwndDlg); + goto stop; + } + else if (!TCCopyFile(srcPath, dstPath)) + { + handleWin32Error(hwndDlg, SRC_POS); + goto stop; + } + } + + // Expander + if (copyExpander) + { + // Expander 32-bit + StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCryptExpander.exe", appDir); + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCryptExpander.exe", dstDir); + if (!VerifyModuleSignature (srcPath)) + { + Error ("DIST_PACKAGE_CORRUPTED", hwndDlg); + goto stop; + } + else if (!TCCopyFile (srcPath, dstPath)) + { + handleWin32Error (hwndDlg, SRC_POS); + goto stop; + } + + // Expander 64-bit + StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCryptExpander-x64.exe", appDir); + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCryptExpander-x64.exe", dstDir); + if (!VerifyModuleSignature (srcPath)) + { + Error ("DIST_PACKAGE_CORRUPTED", hwndDlg); + goto stop; + } + else if (!TCCopyFile (srcPath, dstPath)) + { + handleWin32Error (hwndDlg, SRC_POS); + goto stop; + } + + // Expander ARM 64-bit + StringCbPrintfW(srcPath, sizeof(srcPath), L"%s\\VeraCryptExpander-arm64.exe", appDir); + StringCbPrintfW(dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCryptExpander-arm64.exe", dstDir); + if (!VerifyModuleSignature(srcPath)) + { + Error("DIST_PACKAGE_CORRUPTED", hwndDlg); + goto stop; + } + else if (!TCCopyFile(srcPath, dstPath)) + { + handleWin32Error(hwndDlg, SRC_POS); + goto stop; + } + } + + // Driver + StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\veracrypt.sys", appDir); + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\veracrypt.sys", dstDir); + if (!VerifyModuleSignature (srcPath)) + { + Error ("DIST_PACKAGE_CORRUPTED", hwndDlg); + goto stop; + } + else if (!TCCopyFile (srcPath, dstPath)) { handleWin32Error (hwndDlg, SRC_POS); goto stop; } - } - // Expander - if (copyExpander) - { - // Expander 32-bit - if (Is64BitOs () && !IsNonInstallMode ()) - StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCryptExpander-x86.exe", appDir); - else - StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCryptExpander.exe", appDir); - StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCryptExpander.exe", dstDir); - if (!TCCopyFile (srcPath, dstPath)) + // Driver x64 + StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\veracrypt-x64.sys", appDir); + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\veracrypt-x64.sys", dstDir); + if (!VerifyModuleSignature (srcPath)) + { + Error ("DIST_PACKAGE_CORRUPTED", hwndDlg); + goto stop; + } + else if (!TCCopyFile (srcPath, dstPath)) { handleWin32Error (hwndDlg, SRC_POS); goto stop; } - // Expander 64-bit - if (Is64BitOs () && !IsNonInstallMode ()) - StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCryptExpander.exe", appDir); - else - StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCryptExpander-x64.exe", appDir); - StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCryptExpander-x64.exe", dstDir); - if (!TCCopyFile (srcPath, dstPath)) + // Driver ARM64 + StringCbPrintfW(srcPath, sizeof(srcPath), L"%s\\veracrypt-arm64.sys", appDir); + StringCbPrintfW(dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\veracrypt-arm64.sys", dstDir); + if (!VerifyModuleSignature(srcPath)) { - handleWin32Error (hwndDlg, SRC_POS); + Error("DIST_PACKAGE_CORRUPTED", hwndDlg); + goto stop; + } + else if (!TCCopyFile(srcPath, dstPath)) + { + handleWin32Error(hwndDlg, SRC_POS); goto stop; } } - - // Driver - StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\veracrypt.sys", appDir); - StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\veracrypt.sys", dstDir); - if (!TCCopyFile (srcPath, dstPath)) + else { - handleWin32Error (hwndDlg, SRC_POS); - goto stop; - } + int fileNo = 0; + BOOL bMsiX64Case = FALSE; + // get file from the Setup binary after checking its signature and its version + StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt COMReg.exe", appDir); // MSI installation case + if (FileExists(srcPath)) + { + bMsiX64Case = TRUE; + } + else + StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt Setup.exe", appDir); // EXE installation case - // Driver x64 - StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\veracrypt-x64.sys", appDir); - StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\veracrypt-x64.sys", dstDir); - if (!TCCopyFile (srcPath, dstPath)) - { - handleWin32Error (hwndDlg, SRC_POS); - goto stop; + FreeAllFileBuffers (); + + if (!VerifyPackageIntegrity (srcPath) || !SelfExtractInMemory (srcPath, TRUE) || (!bMsiX64Case && (Decompressed_Files_Count != NBR_COMPRESSED_FILES))) + { + MessageBoxW (hwndDlg, GetString ("DIST_PACKAGE_CORRUPTED"), lpszTitle, MB_ICONEXCLAMATION); + goto stop; + } + + for (fileNo = 0; fileNo < Decompressed_Files_Count; fileNo++) + { + wchar_t fileName [TC_MAX_PATH] = {0}; + + // Filename + StringCchCopyNW (fileName, ARRAYSIZE(fileName), Decompressed_Files[fileNo].fileName, Decompressed_Files[fileNo].fileNameLength); + + if (wcscmp (fileName, L"VeraCrypt.exe") == 0) + { + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCrypt.exe", dstDir); + } + else if (wcscmp (fileName, L"VeraCrypt-x64.exe") == 0) + { + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCrypt-x64.exe", dstDir); + } + else if (wcscmp(fileName, L"VeraCrypt-arm64.exe") == 0) + { + StringCbPrintfW(dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCrypt-arm64.exe", dstDir); + } + else if (wcscmp (fileName, L"veracrypt.sys") == 0) + { + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\veracrypt.sys", dstDir); + } + else if (wcscmp (fileName, L"veracrypt-x64.sys") == 0) + { + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\veracrypt-x64.sys", dstDir); + } + else if (wcscmp(fileName, L"veracrypt-arm64.sys") == 0) + { + StringCbPrintfW(dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\veracrypt-arm64.sys", dstDir); + } + else if (copyWizard && (wcscmp (fileName, L"VeraCrypt Format.exe") == 0)) + { + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCrypt Format.exe", dstDir); + } + else if (copyWizard && (wcscmp (fileName, L"VeraCrypt Format-x64.exe") == 0)) + { + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCrypt Format-x64.exe", dstDir); + } + else if (copyWizard && (wcscmp(fileName, L"VeraCrypt Format-arm64.exe") == 0)) + { + StringCbPrintfW(dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCrypt Format-arm64.exe", dstDir); + } + else if (copyExpander && (wcscmp (fileName, L"VeraCryptExpander.exe") == 0)) + { + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCryptExpander.exe", dstDir); + } + else if (copyExpander && (wcscmp (fileName, L"VeraCryptExpander-x64.exe") == 0)) + { + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCryptExpander-x64.exe", dstDir); + } + else if (copyExpander && (wcscmp(fileName, L"VeraCryptExpander-arm64.exe") == 0)) + { + StringCbPrintfW(dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCryptExpander-arm64.exe", dstDir); + } + else + continue; + + if (!SaveBufferToFile ( + (char *) Decompressed_Files[fileNo].fileContent, + dstPath, + Decompressed_Files[fileNo].fileLength, + FALSE, FALSE)) + { + wchar_t szTmp[512]; + + StringCbPrintfW (szTmp, sizeof (szTmp), GetString ("CANNOT_WRITE_FILE_X"), dstPath); + MessageBoxW (hwndDlg, szTmp, lpszTitle, MB_ICONERROR | MB_SETFOREGROUND | MB_TOPMOST); + goto stop; + } + } + + if (bMsiX64Case) + { + // Main app + StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt.exe", appDir); + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCrypt-x64.exe", dstDir); + if (!VerifyModuleSignature (srcPath)) + { + Error ("DIST_PACKAGE_CORRUPTED", hwndDlg); + goto stop; + } + else if (!TCCopyFile (srcPath, dstPath)) + { + handleWin32Error (hwndDlg, SRC_POS); + goto stop; + } + + // Wizard + if (copyWizard) + { + StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCrypt Format.exe", appDir); + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCrypt Format-x64.exe", dstDir); + if (!VerifyModuleSignature (srcPath)) + { + Error ("DIST_PACKAGE_CORRUPTED", hwndDlg); + goto stop; + } + else if (!TCCopyFile (srcPath, dstPath)) + { + handleWin32Error (hwndDlg, SRC_POS); + goto stop; + } + } + + // Expander + if (copyExpander) + { + StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\VeraCryptExpander.exe", appDir); + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\VeraCryptExpander-x64.exe", dstDir); + if (!VerifyModuleSignature (srcPath)) + { + Error ("DIST_PACKAGE_CORRUPTED", hwndDlg); + goto stop; + } + else if (!TCCopyFile (srcPath, dstPath)) + { + handleWin32Error (hwndDlg, SRC_POS); + goto stop; + } + } + + // Driver + StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\veracrypt.sys", appDir); + StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\veracrypt-x64.sys", dstDir); + if (!VerifyModuleSignature (srcPath)) + { + Error ("DIST_PACKAGE_CORRUPTED", hwndDlg); + goto stop; + } + else if (!TCCopyFile (srcPath, dstPath)) + { + handleWin32Error (hwndDlg, SRC_POS); + goto stop; + } + } } if (strcmp (GetPreferredLangId (), "en") != 0) @@ -4503,7 +4936,11 @@ BOOL CALLBACK TravelerDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa } StringCbPrintfW (srcPath, sizeof(srcPath), L"%s\\Languages\\Language.%hs.xml", appDir, GetPreferredLangId ()); StringCbPrintfW (dstPath, sizeof(dstPath), L"%s\\VeraCrypt\\Languages\\Language.%hs.xml", dstDir, GetPreferredLangId ()); - TCCopyFile (srcPath, dstPath); + if (!TCCopyFile (srcPath, dstPath)) + { + handleWin32Error (hwndDlg, SRC_POS); + goto stop; + } } // AutoRun @@ -4542,6 +4979,7 @@ BOOL CALLBACK TravelerDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPa MessageBoxW (hwndDlg, GetString ("TRAVELER_DISK_CREATED"), lpszTitle, MB_ICONINFORMATION); stop: + FreeAllFileBuffers (); NormalCursor (); return 1; } @@ -4677,7 +5115,7 @@ LPARAM GetItemLong (HWND hTree, int itemNo) return item.lParam; } -static int AskVolumePassword (HWND hwndDlg, Password *password, int *pkcs5, int *pim, BOOL* truecryptMode, char *titleStringId, BOOL enableMountOptions) +static int AskVolumePassword (HWND hwndDlg, Password *password, int *pkcs5, int *pim, char *titleStringId, BOOL enableMountOptions) { INT_PTR result; PasswordDlgParam dlgParam; @@ -4688,7 +5126,6 @@ static int AskVolumePassword (HWND hwndDlg, Password *password, int *pkcs5, int dlgParam.password = password; dlgParam.pkcs5 = pkcs5; dlgParam.pim = pim; - dlgParam.truecryptMode = truecryptMode; result = SecureDesktopDialogBoxParam (hInst, MAKEINTRESOURCEW (IDD_PASSWORD_DLG), hwndDlg, @@ -4699,7 +5136,6 @@ static int AskVolumePassword (HWND hwndDlg, Password *password, int *pkcs5, int password->Length = 0; *pkcs5 = 0; *pim = -1; - *truecryptMode = FALSE; burn (&mountOptions.ProtectedHidVolPassword, sizeof (mountOptions.ProtectedHidVolPassword)); burn (&mountOptions.ProtectedHidVolPkcs5Prf, sizeof (mountOptions.ProtectedHidVolPkcs5Prf)); } @@ -4709,12 +5145,11 @@ static int AskVolumePassword (HWND hwndDlg, Password *password, int *pkcs5, int // GUI actions -static BOOL Mount (HWND hwndDlg, int nDosDriveNo, wchar_t *szFileName, int pim, int pkcs5, int trueCryptMode) +static BOOL Mount (HWND hwndDlg, int nDosDriveNo, wchar_t *szFileName, int pim, int pkcs5) { BOOL status = FALSE; wchar_t fileName[MAX_PATH]; int mounted = 0, EffectiveVolumePkcs5 = 0; - BOOL EffectiveVolumeTrueCryptMode = FALSE; int EffectiveVolumePim = (pim < 0)? CmdVolumePim : pim; BOOL bEffectiveCacheDuringMultipleMount = bCmdCacheDuringMultipleMount? TRUE: bCacheDuringMultipleMount; BOOL bEffectiveTryEmptyPasswordWhenKeyfileUsed = bCmdTryEmptyPasswordWhenKeyfileUsedValid? bCmdTryEmptyPasswordWhenKeyfileUsed : bTryEmptyPasswordWhenKeyfileUsed; @@ -4730,23 +5165,6 @@ static BOOL Mount (HWND hwndDlg, int nDosDriveNo, wchar_t *szFileName, int pim, else EffectiveVolumePkcs5 = DefaultVolumePkcs5; - if (trueCryptMode >= 0) - EffectiveVolumeTrueCryptMode = (trueCryptMode == 0)? FALSE : TRUE; - else if (CmdVolumeTrueCryptMode) - EffectiveVolumeTrueCryptMode = TRUE; - else - EffectiveVolumeTrueCryptMode = DefaultVolumeTrueCryptMode; - - if (EffectiveVolumeTrueCryptMode) - { - /* No PIM Mode if TrueCrypt Mode specified */ - EffectiveVolumePim = 0; - - /* valdate the effective PRF is compatible with TrueCrypt Mode */ - if (!is_pkcs5_prf_supported (EffectiveVolumePkcs5, TRUE, mountOptions.PartitionInInactiveSysEncScope? PRF_BOOT_MBR : PRF_BOOT_NO)) - EffectiveVolumePkcs5 = 0; - } - bPrebootPasswordDlgMode = mountOptions.PartitionInInactiveSysEncScope; if (nDosDriveNo == -1) @@ -4756,7 +5174,6 @@ static BOOL Mount (HWND hwndDlg, int nDosDriveNo, wchar_t *szFileName, int pim, { VolumePassword.Length = 0; VolumePkcs5 = 0; - VolumeTrueCryptMode = FALSE; VolumePim = -1; } @@ -4804,10 +5221,7 @@ static BOOL Mount (HWND hwndDlg, int nDosDriveNo, wchar_t *szFileName, int pim, if (!bUseCmdVolumePassword) { // First try cached passwords and if they fail ask user for a new one - if (EffectiveVolumeTrueCryptMode) - mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, NULL, EffectiveVolumePkcs5, 0, TRUE, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); - else - mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, NULL, EffectiveVolumePkcs5, EffectiveVolumePim, FALSE, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); + mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, NULL, EffectiveVolumePkcs5, EffectiveVolumePim, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); // If keyfiles are enabled, test empty password first if (!mounted && KeyFilesEnable && FirstKeyFile && bEffectiveTryEmptyPasswordWhenKeyfileUsed) @@ -4816,10 +5230,7 @@ static BOOL Mount (HWND hwndDlg, int nDosDriveNo, wchar_t *szFileName, int pim, KeyFilesApply (hwndDlg, &emptyPassword, FirstKeyFile, szFileName); - if (EffectiveVolumeTrueCryptMode) - mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, &emptyPassword, EffectiveVolumePkcs5, 0, TRUE, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); - else - mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, &emptyPassword, EffectiveVolumePkcs5, EffectiveVolumePim, FALSE, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); + mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, &emptyPassword, EffectiveVolumePkcs5, EffectiveVolumePim, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); burn (&emptyPassword, sizeof (emptyPassword)); } @@ -4828,11 +5239,8 @@ static BOOL Mount (HWND hwndDlg, int nDosDriveNo, wchar_t *szFileName, int pim, // Test password and/or keyfiles used for the previous volume if (!mounted && bEffectiveCacheDuringMultipleMount && MultipleMountOperationInProgress && VolumePassword.Length != 0) { - // try TrueCrypt mode first as it is quick, only if no custom pim specified - if (EffectiveVolumeTrueCryptMode) - mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, &VolumePassword, EffectiveVolumePkcs5, 0, TRUE, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); - else // if no PIM specified for favorite, we use also the PIM of the previous volume alongside its password. - mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, &VolumePassword, EffectiveVolumePkcs5, (EffectiveVolumePim < 0)? VolumePim : EffectiveVolumePim, FALSE, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); + // if no PIM specified for favorite, we use also the PIM of the previous volume alongside its password. + mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, &VolumePassword, EffectiveVolumePkcs5, (EffectiveVolumePim < 0)? VolumePim : EffectiveVolumePim, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); } NormalCursor (); @@ -4851,25 +5259,21 @@ static BOOL Mount (HWND hwndDlg, int nDosDriveNo, wchar_t *szFileName, int pim, { VolumePassword = CmdVolumePassword; VolumePkcs5 = EffectiveVolumePkcs5; - VolumeTrueCryptMode = EffectiveVolumeTrueCryptMode; VolumePim = EffectiveVolumePim; } else if (!Silent) { int GuiPkcs5 = EffectiveVolumePkcs5; - BOOL GuiTrueCryptMode = EffectiveVolumeTrueCryptMode; int GuiPim = EffectiveVolumePim; StringCbCopyW (PasswordDlgVolume, sizeof(PasswordDlgVolume), szFileName); - if (!AskVolumePassword (hwndDlg, &VolumePassword, &GuiPkcs5, &GuiPim, &GuiTrueCryptMode, NULL, TRUE)) + if (!AskVolumePassword (hwndDlg, &VolumePassword, &GuiPkcs5, &GuiPim, NULL, TRUE)) goto ret; else { VolumePkcs5 = GuiPkcs5; - VolumeTrueCryptMode = GuiTrueCryptMode; VolumePim = GuiPim; burn (&GuiPkcs5, sizeof(GuiPkcs5)); - burn (&GuiTrueCryptMode, sizeof(GuiTrueCryptMode)); burn (&GuiPim, sizeof(GuiPim)); } } @@ -4879,7 +5283,7 @@ static BOOL Mount (HWND hwndDlg, int nDosDriveNo, wchar_t *szFileName, int pim, if (KeyFilesEnable) KeyFilesApply (hwndDlg, &VolumePassword, FirstKeyFile, szFileName); - mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, &VolumePassword, VolumePkcs5, VolumePim, VolumeTrueCryptMode, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, !Silent); + mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, &VolumePassword, VolumePkcs5, VolumePim, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, !Silent); NormalCursor (); // Check for problematic file extensions (exe, dll, sys) @@ -4890,7 +5294,6 @@ static BOOL Mount (HWND hwndDlg, int nDosDriveNo, wchar_t *szFileName, int pim, { burn (&VolumePassword, sizeof (VolumePassword)); burn (&VolumePkcs5, sizeof (VolumePkcs5)); - burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); burn (&VolumePim, sizeof (VolumePim)); } @@ -4926,20 +5329,21 @@ ret: { burn (&VolumePassword, sizeof (VolumePassword)); burn (&VolumePkcs5, sizeof (VolumePkcs5)); - burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); burn (&VolumePim, sizeof (VolumePim)); } burn (&mountOptions.ProtectedHidVolPassword, sizeof (mountOptions.ProtectedHidVolPassword)); burn (&mountOptions.ProtectedHidVolPkcs5Prf, sizeof (mountOptions.ProtectedHidVolPkcs5Prf)); + mountOptions.SkipCachedPasswords = FALSE; + RestoreDefaultKeyFilesParam (); if (UsePreferences) bCacheInDriver = bCacheInDriverDefault; if (status && CloseSecurityTokenSessionsAfterMount && !MultipleMountOperationInProgress) - SecurityToken::CloseAllSessions(); + SecurityToken::CloseAllSessions(); // TODO Use Token return status; } @@ -4951,7 +5355,14 @@ static BOOL Dismount (HWND hwndDlg, int nDosDriveNo) WaitCursor (); if (nDosDriveNo == -2) + { nDosDriveNo = (char) (HIWORD (GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST))) - L'A'); + if (nDosDriveNo < 0 || nDosDriveNo >= 26) + { + NormalCursor (); + return FALSE; + } + } if (bCloseDismountedWindows) { @@ -4965,9 +5376,6 @@ static BOOL Dismount (HWND hwndDlg, int nDosDriveNo) if (bBeep) MessageBeep (0xFFFFFFFF); RefreshMainDlg (hwndDlg); - - if (nCurrentOS == WIN_2000 && RemoteSession && !IsAdmin ()) - LoadDriveLetters (hwndDlg, GetDlgItem (hwndDlg, IDC_DRIVELIST), 0); } NormalCursor (); @@ -4982,7 +5390,7 @@ void __cdecl mountThreadFunction (void *hwndDlgArg) EnableWindow(hwndDlg, FALSE); finally_do_arg2 (HWND, hwndDlg, BOOL, bIsForeground, { EnableWindow(finally_arg, TRUE); if (finally_arg2) BringToForeground (finally_arg); bPrebootPasswordDlgMode = FALSE;}); - Mount (hwndDlg, -1, 0, -1, -1, -1); + Mount (hwndDlg, -1, 0, -1, -1); } typedef struct @@ -5142,9 +5550,6 @@ retry: RefreshMainDlg (hwndDlg); - if (nCurrentOS == WIN_2000 && RemoteSession && !IsAdmin ()) - LoadDriveLetters (hwndDlg, GetDlgItem (hwndDlg, IDC_DRIVELIST), 0); - NormalCursor(); if (unmount.nReturnCode != 0) @@ -5160,21 +5565,18 @@ retry: goto retry; } - if (IsOSAtLeast (WIN_7)) + // Undo SHCNE_DRIVEREMOVED + if ( DeviceIoControl (hDriver, TC_IOCTL_GET_MOUNTED_VOLUMES, NULL, 0, &mountList, sizeof (mountList), &dwResult, NULL) + && mountList.ulMountedDrives + && (mountList.ulMountedDrives < (1 << 26)) + ) { - // Undo SHCNE_DRIVEREMOVED - if ( DeviceIoControl (hDriver, TC_IOCTL_GET_MOUNTED_VOLUMES, NULL, 0, &mountList, sizeof (mountList), &dwResult, NULL) - && mountList.ulMountedDrives - && (mountList.ulMountedDrives < (1 << 26)) - ) + for (i = 0; i < 26; i++) { - for (i = 0; i < 26; i++) + if (mountList.ulMountedDrives & (1 << i)) { - if (mountList.ulMountedDrives & (1 << i)) - { - wchar_t root[] = { (wchar_t) i + L'A', L':', L'\\', 0 }; - SHChangeNotify (SHCNE_DRIVEADD, SHCNF_PATH, root, NULL); - } + wchar_t root[] = { (wchar_t) i + L'A', L':', L'\\', 0 }; + SHChangeNotify (SHCNE_DRIVEADD, SHCNF_PATH, root, NULL); } } } @@ -5182,7 +5584,7 @@ retry: return FALSE; } - if (interact) + if (interact && !Silent) MessageBoxW (hwndDlg, GetString ("UNMOUNT_FAILED"), lpszTitle, MB_ICONERROR); } else @@ -5202,18 +5604,16 @@ static BOOL MountAllDevicesThreadCode (HWND hwndDlg, BOOL bPasswordPrompt) int mountedVolCount = 0; vector <HostDevice> devices; int EffectiveVolumePkcs5 = CmdVolumePkcs5; - BOOL EffectiveVolumeTrueCryptMode = CmdVolumeTrueCryptMode; /* Priority is given to command line parameters * Default values used only when nothing specified in command line */ if (EffectiveVolumePkcs5 == 0) EffectiveVolumePkcs5 = DefaultVolumePkcs5; - if (!EffectiveVolumeTrueCryptMode) - EffectiveVolumeTrueCryptMode = DefaultVolumeTrueCryptMode; VolumePassword.Length = 0; mountOptions = defaultMountOptions; + mountOptions.SkipCachedPasswords = FALSE; bPrebootPasswordDlgMode = FALSE; VolumePim = -1; @@ -5231,18 +5631,15 @@ static BOOL MountAllDevicesThreadCode (HWND hwndDlg, BOOL bPasswordPrompt) if (!CmdVolumePasswordValid && bPasswordPrompt) { int GuiPkcs5 = EffectiveVolumePkcs5; - BOOL GuiTrueCryptMode = EffectiveVolumeTrueCryptMode; int GuiPim = CmdVolumePim; PasswordDlgVolume[0] = '\0'; - if (!AskVolumePassword (hwndDlg, &VolumePassword, &GuiPkcs5, &GuiPim, &GuiTrueCryptMode, NULL, TRUE)) + if (!AskVolumePassword (hwndDlg, &VolumePassword, &GuiPkcs5, &GuiPim, NULL, TRUE)) goto ret; else { VolumePkcs5 = GuiPkcs5; - VolumeTrueCryptMode = GuiTrueCryptMode; VolumePim = GuiPim; burn (&GuiPkcs5, sizeof(GuiPkcs5)); - burn (&GuiTrueCryptMode, sizeof(GuiTrueCryptMode)); burn (&GuiPim, sizeof(GuiPim)); } } @@ -5251,7 +5648,6 @@ static BOOL MountAllDevicesThreadCode (HWND hwndDlg, BOOL bPasswordPrompt) bPasswordPrompt = FALSE; VolumePassword = CmdVolumePassword; VolumePkcs5 = EffectiveVolumePkcs5; - VolumeTrueCryptMode = EffectiveVolumeTrueCryptMode; VolumePim = CmdVolumePim; } @@ -5335,8 +5731,8 @@ static BOOL MountAllDevicesThreadCode (HWND hwndDlg, BOOL bPasswordPrompt) } // First try user password then cached passwords - if ((mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, &VolumePassword, VolumePkcs5, VolumePim, VolumeTrueCryptMode, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, TRUE, FALSE)) > 0 - || ((VolumePassword.Length > 0) && ((mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, NULL, VolumePkcs5, VolumePim, VolumeTrueCryptMode, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, TRUE, FALSE)) > 0))) + if ((mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, &VolumePassword, VolumePkcs5, VolumePim, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, TRUE, FALSE)) > 0 + || ((VolumePassword.Length > 0) && ((mounted = MountVolume (hwndDlg, nDosDriveNo, szFileName, NULL, VolumePkcs5, VolumePim, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, TRUE, FALSE)) > 0))) { // A volume has been successfully mounted @@ -5415,7 +5811,6 @@ static BOOL MountAllDevicesThreadCode (HWND hwndDlg, BOOL bPasswordPrompt) { burn (&VolumePassword, sizeof (VolumePassword)); burn (&VolumePkcs5, sizeof (VolumePkcs5)); - burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); burn (&VolumePim, sizeof (VolumePim)); burn (&mountOptions.ProtectedHidVolPassword, sizeof (mountOptions.ProtectedHidVolPassword)); burn (&mountOptions.ProtectedHidVolPkcs5Prf, sizeof (mountOptions.ProtectedHidVolPkcs5Prf)); @@ -5439,14 +5834,13 @@ static BOOL MountAllDevicesThreadCode (HWND hwndDlg, BOOL bPasswordPrompt) } if (status && CloseSecurityTokenSessionsAfterMount) - SecurityToken::CloseAllSessions(); + SecurityToken::CloseAllSessions(); // TODO Use Token ret: MultipleMountOperationInProgress = FALSE; burn (&VolumePassword, sizeof (VolumePassword)); burn (&VolumePkcs5, sizeof (VolumePkcs5)); - burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); burn (&VolumePim, sizeof (VolumePim)); burn (&mountOptions.ProtectedHidVolPassword, sizeof (mountOptions.ProtectedHidVolPassword)); burn (&mountOptions.ProtectedHidVolPkcs5Prf, sizeof (mountOptions.ProtectedHidVolPkcs5Prf)); @@ -5485,7 +5879,10 @@ static BOOL MountAllDevices (HWND hwndDlg, BOOL bPasswordPrompt) param.bPasswordPrompt = bPasswordPrompt; param.bRet = FALSE; - ShowWaitDialog (hwndDlg, FALSE, mountAllDevicesThreadProc, ¶m); + if (Silent) + mountAllDevicesThreadProc (¶m, hwndDlg); + else + ShowWaitDialog (hwndDlg, FALSE, mountAllDevicesThreadProc, ¶m); return param.bRet; } @@ -5875,8 +6272,6 @@ static void DecryptNonSysDevice (HWND hwndDlg, BOOL bResolveAmbiguousSelection, return; } - WaitCursor(); - // Make sure the user is not attempting to decrypt a partition on an entirely encrypted system drive. if (IsNonSysPartitionOnSysDrive (scPath.c_str ()) == 1) { @@ -5894,8 +6289,6 @@ static void DecryptNonSysDevice (HWND hwndDlg, BOOL bResolveAmbiguousSelection, { // The system drive MAY be entirely encrypted (external access without PBA) and the potentially encrypted OS is not running - NormalCursor (); - Warning ("CANT_DECRYPT_PARTITION_ON_ENTIRELY_ENCRYPTED_SYS_DRIVE_UNSURE", hwndDlg); // We allow the user to continue as we don't know if the drive is really an encrypted system drive. @@ -6124,6 +6517,14 @@ static void ShowSystemEncryptionStatus (HWND hwndDlg) if (GetAsyncKeyState (VK_SHIFT) < 0 && GetAsyncKeyState (VK_CONTROL) < 0) { // Ctrl+Shift held (for debugging purposes) + int64 encryptedRatio = 0; + if (BootEncStatus.DriveEncrypted + && (BootEncStatus.ConfiguredEncryptedAreaStart >= 0) + && (BootEncStatus.ConfiguredEncryptedAreaEnd >= BootEncStatus.ConfiguredEncryptedAreaStart) + ) + { + encryptedRatio = (BootEncStatus.EncryptedAreaEnd + 1 - BootEncStatus.EncryptedAreaStart) * 100I64 / (BootEncStatus.ConfiguredEncryptedAreaEnd + 1 - BootEncStatus.ConfiguredEncryptedAreaStart); + } DebugMsgBox ("Debugging information for system encryption:\n\nDeviceFilterActive: %d\nBootLoaderVersion: %x\nSetupInProgress: %d\nSetupMode: %d\nVolumeHeaderPresent: %d\nDriveMounted: %d\nDriveEncrypted: %d\n" "HiddenSystem: %d\nHiddenSystemPartitionStart: %I64d\n" @@ -6141,7 +6542,7 @@ static void ShowSystemEncryptionStatus (HWND hwndDlg) BootEncStatus.ConfiguredEncryptedAreaEnd, BootEncStatus.EncryptedAreaStart, BootEncStatus.EncryptedAreaEnd, - !BootEncStatus.DriveEncrypted ? 0 : (BootEncStatus.EncryptedAreaEnd + 1 - BootEncStatus.EncryptedAreaStart) * 100I64 / (BootEncStatus.ConfiguredEncryptedAreaEnd + 1 - BootEncStatus.ConfiguredEncryptedAreaStart)); + encryptedRatio); } if (!BootEncStatus.DriveEncrypted && !BootEncStatus.DriveMounted) @@ -6166,7 +6567,7 @@ static void ResumeInterruptedNonSysInplaceEncProcess (BOOL bDecrypt) BOOL SelectContainer (HWND hwndDlg) { - if (BrowseFiles (hwndDlg, "OPEN_VOL_TITLE", szFileName, bHistory, FALSE, NULL) == FALSE) + if (BrowseFiles (hwndDlg, "OPEN_VOL_TITLE", szFileName, bHistory, FALSE) == FALSE) return FALSE; AddComboItem (GetDlgItem (hwndDlg, IDC_VOLUME), szFileName, bHistory); @@ -6497,12 +6898,12 @@ void DisplayDriveListContextMenu (HWND hwndDlg, LPARAM lParam) { case IDPM_SELECT_FILE_AND_MOUNT: if (SelectContainer (hwndDlg)) - MountSelectedVolume (hwndDlg, FALSE); + MountSelectedVolume (hwndDlg, FALSE, FALSE); break; case IDPM_SELECT_DEVICE_AND_MOUNT: if (SelectPartition (hwndDlg)) - MountSelectedVolume (hwndDlg, FALSE); + MountSelectedVolume (hwndDlg, FALSE, FALSE); break; case IDPM_CHECK_FILESYS: @@ -6554,6 +6955,7 @@ void DisplayDriveListContextMenu (HWND hwndDlg, LPARAM lParam) else { mountOptions = defaultMountOptions; + mountOptions.SkipCachedPasswords = FALSE; bPrebootPasswordDlgMode = FALSE; if (CheckMountList (hwndDlg, FALSE)) @@ -6577,6 +6979,41 @@ void DisplayDriveListContextMenu (HWND hwndDlg, LPARAM lParam) } } +// broadcast signal to WAITFOR.EXE MailSlot to notify any waiting instance that we are exiting +static void SignalExitCode (int exitCode) +{ + if (ExitMailSlotSpecified) + { + HANDLE hFile; + hFile = CreateFile (ExitMailSlotName, + GENERIC_WRITE, + FILE_SHARE_READ, + (LPSECURITY_ATTRIBUTES) NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + (HANDLE) NULL); + if ((hFile == INVALID_HANDLE_VALUE) && (GetLastError () == ERROR_FILE_NOT_FOUND)) + { + // MailSlot not found, wait 1 second and try again in case we exited too quickly + Sleep (1000); + hFile = CreateFile (ExitMailSlotName, + GENERIC_WRITE, + FILE_SHARE_READ, + (LPSECURITY_ATTRIBUTES) NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + (HANDLE) NULL); + } + if (hFile != INVALID_HANDLE_VALUE) + { + char szMsg[64]; + DWORD cbWritten; + StringCbPrintfA (szMsg, sizeof (szMsg), "VeraCrypt Exit %d", exitCode); + WriteFile(hFile, szMsg, (DWORD) (strlen (szMsg) +1), &cbWritten, (LPOVERLAPPED) NULL); + CloseHandle (hFile); + } + } +} /* Except in response to the WM_INITDIALOG and WM_ENDSESSION messages, the dialog box procedure should return nonzero if it processes a message, and zero if it does not. */ @@ -6607,11 +7044,15 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa bShowDisconnectedNetworkDrives = FALSE; bHideWaitingDialog = FALSE; bUseSecureDesktop = FALSE; + bUseLegacyMaxPasswordLength = FALSE; ResetWrongPwdRetryCount (); ExtractCommandLine (hwndDlg, (wchar_t *) lParam); + if (Silent && !Quit) + Silent = FALSE; + try { BootEncObj->SetParentWindow (hwndDlg); @@ -6637,9 +7078,25 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa // General preferences LoadSettings (hwndDlg); + // Save language to XML configuration file if it has been selected in the setup + // so that other VeraCrypt programs will pick it up + if (bLanguageSetInSetup) + SaveSettings (hwndDlg); + + // Keyfiles LoadDefaultKeyFilesParam (); RestoreDefaultKeyFilesParam (); + + // if maximum password length is set to legacy value, abort if password in command line is longer + if (bUseLegacyMaxPasswordLength && CmdVolumePasswordValid && (CmdVolumePassword.Length > MAX_LEGACY_PASSWORD)) + AbortProcess ("COMMAND_LINE_ERROR"); + } + + if (EnableMemoryProtection) + { + /* Protect this process memory from being accessed by non-admin users */ + ActivateMemoryProtection (); } if (ComServerMode) @@ -6727,7 +7184,6 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa { BOOL mounted = FALSE; int EffectiveVolumePkcs5 = CmdVolumePkcs5; - BOOL EffectiveVolumeTrueCryptMode = CmdVolumeTrueCryptMode; BOOL bEffectiveTryEmptyPasswordWhenKeyfileUsed = bCmdTryEmptyPasswordWhenKeyfileUsedValid? bCmdTryEmptyPasswordWhenKeyfileUsed : bTryEmptyPasswordWhenKeyfileUsed; if (!VolumePathExists (szFileName)) @@ -6741,8 +7197,6 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa */ if (EffectiveVolumePkcs5 == 0) EffectiveVolumePkcs5 = DefaultVolumePkcs5; - if (!EffectiveVolumeTrueCryptMode) - EffectiveVolumeTrueCryptMode = DefaultVolumeTrueCryptMode; // Command line password or keyfiles if (CmdVolumePassword.Length != 0 || (FirstCmdKeyFile && (CmdVolumePasswordValid || bEffectiveTryEmptyPasswordWhenKeyfileUsed))) @@ -6753,7 +7207,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa KeyFilesApply (hwndDlg, &CmdVolumePassword, FirstCmdKeyFile, szFileName); mounted = MountVolume (hwndDlg, szDriveLetter[0] - L'A', - szFileName, &CmdVolumePassword, EffectiveVolumePkcs5, CmdVolumePim, EffectiveVolumeTrueCryptMode, bCacheInDriver, bIncludePimInCache, bForceMount, + szFileName, &CmdVolumePassword, EffectiveVolumePkcs5, CmdVolumePim, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, reportBadPasswd); burn (&CmdVolumePassword, sizeof (CmdVolumePassword)); @@ -6761,13 +7215,13 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa else { // Cached password - mounted = MountVolume (hwndDlg, szDriveLetter[0] - L'A', szFileName, NULL, EffectiveVolumePkcs5, CmdVolumePim, EffectiveVolumeTrueCryptMode, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); + mounted = MountVolume (hwndDlg, szDriveLetter[0] - L'A', szFileName, NULL, EffectiveVolumePkcs5, CmdVolumePim, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, Silent, FALSE); } if (FirstCmdKeyFile) { KeyFileRemoveAll (&FirstKeyFile); - FirstKeyFile = FirstCmdKeyFile; + KeyFileCloneAll (FirstCmdKeyFile, &FirstKeyFile); KeyFilesEnable = TRUE; } @@ -6776,20 +7230,17 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa { int GuiPkcs5 = EffectiveVolumePkcs5; int GuiPim = CmdVolumePim; - BOOL GuiTrueCryptMode = EffectiveVolumeTrueCryptMode; VolumePassword.Length = 0; StringCbCopyW (PasswordDlgVolume, sizeof(PasswordDlgVolume),szFileName); - if (!AskVolumePassword (hwndDlg, &VolumePassword, &GuiPkcs5, &GuiPim, &GuiTrueCryptMode, NULL, TRUE)) + if (!AskVolumePassword (hwndDlg, &VolumePassword, &GuiPkcs5, &GuiPim, NULL, TRUE)) break; else { VolumePkcs5 = GuiPkcs5; VolumePim = GuiPim; - VolumeTrueCryptMode = GuiTrueCryptMode; burn (&GuiPkcs5, sizeof(GuiPkcs5)); burn (&GuiPim, sizeof(GuiPim)); - burn (&GuiTrueCryptMode, sizeof(GuiTrueCryptMode)); } WaitCursor (); @@ -6797,12 +7248,11 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (KeyFilesEnable && FirstKeyFile) KeyFilesApply (hwndDlg, &VolumePassword, FirstKeyFile, szFileName); - mounted = MountVolume (hwndDlg, szDriveLetter[0] - L'A', szFileName, &VolumePassword, VolumePkcs5, VolumePim, VolumeTrueCryptMode, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, FALSE, TRUE); + mounted = MountVolume (hwndDlg, szDriveLetter[0] - L'A', szFileName, &VolumePassword, VolumePkcs5, VolumePim, bCacheInDriver, bIncludePimInCache, bForceMount, &mountOptions, FALSE, TRUE); burn (&VolumePassword, sizeof (VolumePassword)); burn (&VolumePkcs5, sizeof (VolumePkcs5)); burn (&VolumePim, sizeof (VolumePim)); - burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); burn (&mountOptions.ProtectedHidVolPassword, sizeof (mountOptions.ProtectedHidVolPassword)); burn (&mountOptions.ProtectedHidVolPkcs5Prf, sizeof (mountOptions.ProtectedHidVolPkcs5Prf)); @@ -6824,10 +7274,10 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (bExplore) OpenVolumeExplorerWindow (szDriveLetter[0] - L'A'); - RefreshMainDlg(hwndDlg); if(!Silent) { + RefreshMainDlg(hwndDlg); // Check for problematic file extensions (exe, dll, sys) if (CheckFileExtension (szFileName)) Warning ("EXE_FILE_EXTENSION_MOUNT_WARNING", hwndDlg); @@ -6903,7 +7353,10 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (Quit) { if (TaskBarIconMutex == NULL) + { + SignalExitCode (exitCode); exit (exitCode); + } MainWindowHidden = TRUE; @@ -6915,8 +7368,18 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa { if (TaskBarIconMutex) TaskBarIconRemove (hwndDlg); + SignalExitCode (exitCode); exit (exitCode); } + else + { + if (Silent) + { + Silent = FALSE; + InitMainDialog (hwndDlg); + RefreshMainDlg(hwndDlg); + } + } } // No command line arguments or only /volume => bring active instance @@ -7007,7 +7470,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa } if (TaskBarIconMutex != NULL) - RegisterWtsNotification(hwndDlg); + RegisterWtsAndPowerNotification(hwndDlg); DoPostInstallTasks (hwndDlg); ResetCurrentDirectory (); } @@ -7069,7 +7532,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (bWipeCacheOnAutoDismount) { DeviceIoControl (hDriver, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0, &dwResult, NULL); - SecurityToken::CloseAllSessions(); + SecurityToken::CloseAllSessions(); // TODO Use Token } DismountAll (hwndDlg, bForceAutoDismount, TRUE, UNMOUNT_MAX_AUTO_RETRIES, UNMOUNT_AUTO_RETRY_DELAY); @@ -7092,7 +7555,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa } TaskBarIconRemove (hwndDlg); - UnregisterWtsNotification(hwndDlg); + UnregisterWtsAndPowerNotification(hwndDlg); } EndMainDlg (hwndDlg); localcleanup (); @@ -7108,7 +7571,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (bWipeCacheOnAutoDismount) { DeviceIoControl (hDriver, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0, &dwResult, NULL); - SecurityToken::CloseAllSessions(); + SecurityToken::CloseAllSessions(); // TODO Use Token } DismountAll (hwndDlg, bForceAutoDismount, TRUE, UNMOUNT_MAX_AUTO_RETRIES, UNMOUNT_AUTO_RETRY_DELAY); @@ -7119,7 +7582,8 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa { if (wParam == TIMER_ID_UPDATE_DEVICE_LIST) { - UpdateMountableHostDeviceList (); + if (NeedPeriodicDeviceListUpdate) + UpdateMountableHostDeviceList (); } else { @@ -7164,7 +7628,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (bWipeCacheOnAutoDismount) { DeviceIoControl (hDriver, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0, &dwResult, NULL); - SecurityToken::CloseAllSessions(); + SecurityToken::CloseAllSessions(); // TODO Use Token } DismountAll (hwndDlg, bForceAutoDismount, FALSE, UNMOUNT_MAX_AUTO_RETRIES, UNMOUNT_AUTO_RETRY_DELAY); @@ -7309,7 +7773,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa && GetDriverRefCount () < 2) { TaskBarIconRemove (hwndDlg); - UnregisterWtsNotification(hwndDlg); + UnregisterWtsAndPowerNotification(hwndDlg); EndMainDlg (hwndDlg); } } @@ -7436,7 +7900,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa EnumWindows (CloseTCWindowsEnum, 0); TaskBarIconRemove (hwndDlg); - UnregisterWtsNotification(hwndDlg); + UnregisterWtsAndPowerNotification(hwndDlg); SendMessage (hwndDlg, WM_COMMAND, sel, 0); } } @@ -7457,7 +7921,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa case TC_APPMSG_CLOSE_BKG_TASK: if (TaskBarIconMutex != NULL) TaskBarIconRemove (hwndDlg); - UnregisterWtsNotification(hwndDlg); + UnregisterWtsAndPowerNotification(hwndDlg); return 1; @@ -7570,14 +8034,31 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa nSelectedDriveIndex = ((LPNMITEMACTIVATE)lParam)->iItem; if (LOWORD(state) == TC_MLIST_ITEM_NONSYS_VOL || LOWORD(state) == TC_MLIST_ITEM_SYS_PARTITION) { - // Open explorer window for mounted volume - WaitCursor (); - OpenVolumeExplorerWindow (HIWORD(state) - L'A'); - NormalCursor (); + VOLUME_PROPERTIES_STRUCT prop; + DWORD dwResult; + + memset (&prop, 0, sizeof(prop)); + prop.driveNo = HIWORD (state) - L'A'; + + if (DeviceIoControl (hDriver, TC_IOCTL_GET_VOLUME_PROPERTIES, &prop, sizeof (prop), &prop, sizeof (prop), &dwResult, NULL) + && dwResult + && prop.mountDisabled + ) + { + Warning ("MOUNTED_VOLUME_NOT_ASSOCIATED", hwndDlg); + } + else + { + // Open explorer window for mounted volume + WaitCursor (); + OpenVolumeExplorerWindow (HIWORD(state) - L'A'); + NormalCursor (); + } } else if (LOWORD (GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST))) == TC_MLIST_ITEM_FREE) { mountOptions = defaultMountOptions; + mountOptions.SkipCachedPasswords = FALSE; bPrebootPasswordDlgMode = FALSE; if (GetAsyncKeyState (VK_CONTROL) < 0) @@ -7591,7 +8072,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa mountOptions.ProtectedHidVolPkcs5Prf = CmdVolumePkcs5; mountOptions.ProtectedHidVolPim = CmdVolumePim; - if (IDCANCEL == DialogBoxParamW (hInst, + if (IDCANCEL == SecureDesktopDialogBoxParam (hInst, MAKEINTRESOURCEW (IDD_MOUNT_OPTIONS), hwndDlg, (DLGPROC) MountOptionsDlgProc, (LPARAM) &mountOptions)) return 1; @@ -7627,6 +8108,18 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa } } } + else + { + LPNMHDR pnmh = (LPNMHDR)lParam; + + if (pnmh->idFrom == IDOK && pnmh->code == BCN_DROPDOWN) + { + // Create a popup menu for the split button + HMENU hmenu = CreateMountNoCacheDropdownMenu(); + HandleMountButtonDropdown(pnmh->hwndFrom, hwndDlg, hmenu); + DestroyMenu(hmenu); + } + } return 0; case WM_ERASEBKGND: @@ -7673,9 +8166,9 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa return 1; } - if ((lw == IDOK || lw == IDM_MOUNT_VOLUME || lw == IDM_MOUNT_VOLUME_OPTIONS)) + if ((lw == IDOK || lw == IDM_MOUNT_VOLUME || lw == IDM_MOUNT_VOLUME_OPTIONS || lw == IDM_MOUNIT_NO_CACHE)) { - MountSelectedVolume (hwndDlg, lw == IDM_MOUNT_VOLUME_OPTIONS); + MountSelectedVolume (hwndDlg, lw == IDM_MOUNT_VOLUME_OPTIONS, lw == IDM_MOUNIT_NO_CACHE); return 1; } @@ -7748,6 +8241,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa { mountOptions = defaultMountOptions; mountOptions.PartitionInInactiveSysEncScope = TRUE; + mountOptions.SkipCachedPasswords = FALSE; bPrebootPasswordDlgMode = TRUE; if (CheckMountList (hwndDlg, FALSE)) @@ -8033,7 +8527,7 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa WaitCursor(); finally_do ({ NormalCursor(); }); - SecurityToken::CloseAllSessions(); + SecurityToken::CloseAllSessions(); // TODO Use Token } InfoBalloon (NULL, "ALL_TOKEN_SESSIONS_CLOSED", hwndDlg); @@ -8117,12 +8611,12 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (bEnableBkgTask) { TaskBarIconAdd (hwndDlg); - RegisterWtsNotification(hwndDlg); + RegisterWtsAndPowerNotification(hwndDlg); } else { TaskBarIconRemove (hwndDlg); - UnregisterWtsNotification(hwndDlg); + UnregisterWtsAndPowerNotification(hwndDlg); if (MainWindowHidden) EndMainDlg (hwndDlg); } @@ -8392,12 +8886,10 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa WaitCursor (); - if (!(nCurrentOS == WIN_2000 && RemoteSession)) - { - BroadcastDeviceChange (DBT_DEVICEREMOVECOMPLETE, 0, ~driveMap); - Sleep (100); - BroadcastDeviceChange (DBT_DEVICEARRIVAL, 0, driveMap); - } + + BroadcastDeviceChange (DBT_DEVICEREMOVECOMPLETE, 0, ~driveMap); + Sleep (100); + BroadcastDeviceChange (DBT_DEVICEARRIVAL, 0, driveMap); LoadDriveLetters (hwndDlg, GetDlgItem (hwndDlg, IDC_DRIVELIST), 0); @@ -8413,7 +8905,8 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa if (lw == IDM_MOUNT_FAVORITE_VOLUMES) { - _beginthread(mountFavoriteVolumeThreadFunction, 0, NULL); + if (0 == _InterlockedCompareExchange(&FavoriteMountOnGoing, 1, 0)) + _beginthread(mountFavoriteVolumeThreadFunction, 0, NULL); return 1; } @@ -8494,13 +8987,16 @@ BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lPa } else { - mountFavoriteVolumeThreadParam* pParam = (mountFavoriteVolumeThreadParam*) calloc(1, sizeof(mountFavoriteVolumeThreadParam)); - pParam->systemFavorites = FALSE; - pParam->logOnMount = FALSE; - pParam->hotKeyMount = FALSE; - pParam->favoriteVolumeToMount = &FavoriteVolumes[favoriteIndex]; + if (0 == _InterlockedCompareExchange(&FavoriteMountOnGoing, 1, 0)) + { + mountFavoriteVolumeThreadParam* pParam = (mountFavoriteVolumeThreadParam*) calloc(1, sizeof(mountFavoriteVolumeThreadParam)); + pParam->systemFavorites = FALSE; + pParam->logOnMount = FALSE; + pParam->hotKeyMount = FALSE; + pParam->favoriteVolumeToMount = &FavoriteVolumes[favoriteIndex]; - _beginthread(mountFavoriteVolumeThreadFunction, 0, pParam); + _beginthread(mountFavoriteVolumeThreadFunction, 0, pParam); + } } } @@ -8589,9 +9085,11 @@ void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) wchar_t **lpszCommandLineArgs = NULL; /* Array of command line arguments */ int nNoCommandLineArgs; /* The number of arguments in the array */ wchar_t tmpPath[MAX_PATH * 2]; + wchar_t CmdRawPassword[MAX_PASSWORD + 1]; /* Raw value of password passed from command line */ /* Defaults */ mountOptions.PreserveTimestamp = TRUE; + mountOptions.SkipCachedPasswords = FALSE; if (_wcsicmp (lpszCommandLine, L"-Embedding") == 0) { @@ -8629,11 +9127,13 @@ void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) OptionVolume, CommandWipeCache, OptionPkcs5, - OptionTrueCryptMode, OptionPim, OptionTryEmptyPassword, OptionNoWaitDlg, OptionSecureDesktop, + OptionDisableDeviceUpdate, + OptionEnableMemoryProtection, + OptionSignalExit, }; argument args[]= @@ -8656,12 +9156,14 @@ void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) { OptionSilent, L"/silent", L"/s", FALSE }, { OptionTokenLib, L"/tokenlib", NULL, FALSE }, { OptionTokenPin, L"/tokenpin", NULL, FALSE }, - { OptionTrueCryptMode, L"/truecrypt", L"/tc", FALSE }, { OptionVolume, L"/volume", L"/v", FALSE }, { CommandWipeCache, L"/wipecache", L"/w", FALSE }, { OptionTryEmptyPassword, L"/tryemptypass", NULL, FALSE }, { OptionNoWaitDlg, L"/nowaitdlg", NULL, FALSE }, { OptionSecureDesktop, L"/secureDesktop", NULL, FALSE }, + { OptionDisableDeviceUpdate, L"/disableDeviceUpdate", NULL, FALSE }, + { OptionEnableMemoryProtection, L"/protectMemory", NULL, FALSE }, + { OptionSignalExit, L"/signalExit", NULL, FALSE }, }; argumentspec as; @@ -8752,6 +9254,29 @@ void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) } break; + case OptionDisableDeviceUpdate: + { + DisablePeriodicDeviceListUpdate = TRUE; + } + break; + + case OptionEnableMemoryProtection: + { + EnableMemoryProtection = TRUE; + } + break; + + case OptionSignalExit: + if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, &i, + nNoCommandLineArgs, tmpPath, ARRAYSIZE (tmpPath))) + { + StringCbPrintfW (ExitMailSlotName, sizeof (ExitMailSlotName), L"\\\\.\\mailslot\\WAITFOR.EXE\\%s", tmpPath); + ExitMailSlotSpecified = TRUE; + } + else + AbortProcess ("COMMAND_LINE_ERROR"); + break; + case OptionCache: { wchar_t szTmp[16] = {0}; @@ -8897,6 +9422,10 @@ void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) // get the label StringCbCopyW (mountOptions.Label, sizeof (mountOptions.Label), &szTmp[6]); } + else if (!_wcsicmp (szTmp, L"noattach")) + { + mountOptions.DisableMountManager = TRUE; + } else AbortProcess ("COMMAND_LINE_ERROR"); @@ -8910,19 +9439,20 @@ void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) case OptionPassword: { - wchar_t szTmp[MAX_PASSWORD + 1]; if (HAS_ARGUMENT == GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, - szTmp, ARRAYSIZE (szTmp))) + CmdRawPassword, ARRAYSIZE (CmdRawPassword))) { - int iLen = WideCharToMultiByte (CP_UTF8, 0, szTmp, -1, (char*) CmdVolumePassword.Text, MAX_PASSWORD + 1, NULL, NULL); - burn (szTmp, sizeof (szTmp)); + int iLen = WideCharToMultiByte (CP_UTF8, 0, CmdRawPassword, -1, (char*) CmdVolumePassword.Text, MAX_PASSWORD + 1, NULL, NULL); if (iLen > 0) { CmdVolumePassword.Length = (unsigned __int32) (iLen - 1); CmdVolumePasswordValid = TRUE; } else + { + burn (CmdRawPassword, sizeof (CmdRawPassword)); AbortProcess ("COMMAND_LINE_ERROR"); + } } else AbortProcess ("COMMAND_LINE_ERROR"); @@ -8984,7 +9514,7 @@ void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) case OptionTokenPin: { - wchar_t szTmp[SecurityToken::MaxPasswordLength + 1] = {0}; + wchar_t szTmp[SecurityToken::MaxPasswordLength + 1] = {0}; // TODO Use Token if (GetArgumentValue (lpszCommandLineArgs, &i, nNoCommandLineArgs, szTmp, ARRAYSIZE (szTmp)) == HAS_ARGUMENT) { if (0 == WideCharToMultiByte (CP_UTF8, 0, szTmp, -1, CmdTokenPin, TC_MAX_PATH, nullptr, nullptr)) @@ -9017,8 +9547,8 @@ void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) CmdVolumePkcs5 = SHA512; else if (_wcsicmp(szTmp, L"sha256") == 0) CmdVolumePkcs5 = SHA256; - else if (_wcsicmp(szTmp, L"ripemd160") == 0) - CmdVolumePkcs5 = RIPEMD160; + else if ((_wcsicmp(szTmp, L"blake2s") == 0) || (_wcsicmp(szTmp, L"blake2s-256") == 0)) + CmdVolumePkcs5 = BLAKE2S; else { /* match using internal hash names */ @@ -9054,10 +9584,6 @@ void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) } break; - case OptionTrueCryptMode: - CmdVolumeTrueCryptMode = TRUE; - break; - // no option = file name if there is only one argument default: { @@ -9076,6 +9602,28 @@ void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) } } + if (CmdVolumePasswordValid && CmdMountOptionsValid && bPrebootPasswordDlgMode) + { + /* truncate the password to 64 first characer in case of System Encryption */ + if (lstrlen (CmdRawPassword) > MAX_LEGACY_PASSWORD) + { + int iLen; + wmemset (&CmdRawPassword[MAX_LEGACY_PASSWORD], 0, MAX_PASSWORD + 1 - MAX_LEGACY_PASSWORD); + iLen = WideCharToMultiByte (CP_UTF8, 0, CmdRawPassword, -1, (char*) CmdVolumePassword.Text, MAX_PASSWORD + 1, NULL, NULL); + if (iLen > 0) + { + CmdVolumePassword.Length = (unsigned __int32) (iLen - 1); + } + else + { + burn (CmdRawPassword, sizeof (CmdRawPassword)); + AbortProcess ("COMMAND_LINE_ERROR"); + } + } + } + + burn (CmdRawPassword, sizeof (CmdRawPassword)); + /* Free up the command line arguments */ while (--nNoCommandLineArgs >= 0) { @@ -9089,6 +9637,74 @@ void ExtractCommandLine (HWND hwndDlg, wchar_t *lpszCommandLine) static SERVICE_STATUS SystemFavoritesServiceStatus; static SERVICE_STATUS_HANDLE SystemFavoritesServiceStatusHandle; +static HANDLE SystemFavoriteServiceStopEvent = NULL; +static HDEVNOTIFY SystemFavoriteServiceNotify = NULL; + +DEFINE_GUID(OCL_GUID_DEVCLASS_SOFTWARECOMPONENT, 0x5c4c3332, 0x344d, 0x483c, 0x87, 0x39, 0x25, 0x9e, 0x93, 0x4c, 0x9c, 0xc8); + +// This functions returns a vector containing all devices currently connected to the system +void BuildDeviceList(std::vector<CDevice>& devices) +{ + devices.clear(); + + // Get device info set for all devices + HDEVINFO hDevInfo = SetupDiGetClassDevs(NULL, NULL, NULL, DIGCF_ALLCLASSES | DIGCF_PRESENT); + if (hDevInfo != INVALID_HANDLE_VALUE) + { + SP_DEVINFO_DATA deviceInfoData; + deviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA); + + // Enumerate through all devices in set + for (DWORD i = 0; SetupDiEnumDeviceInfo(hDevInfo, i, &deviceInfoData); i++) + { + // Get device path + WCHAR szDeviceID[MAX_PATH]; + if (CR_SUCCESS == CM_Get_Device_IDW(deviceInfoData.DevInst, szDeviceID, MAX_PATH, 0)) + { + // Add to vector + devices.push_back(CDevice(szDeviceID)); + } + } + + SetupDiDestroyDeviceInfoList(hDevInfo); // Cleanup + } +} + +// This function build a device ID value from the dbcc_name field of a DEV_BROADCAST_DEVICEINTERFACE structure +// In case of error, the device ID is set to an empty string +// Algorithm taken from https://www.codeproject.com/Articles/14500/Detecting-Hardware-Insertion-and-or-Removal#premain174347 +void GetDeviceID(PDEV_BROADCAST_DEVICEINTERFACE pDevInf, WCHAR* szDevId) +{ + szDevId[0] = L'\0'; + if (lstrlen(pDevInf->dbcc_name) < 4) return; + if (lstrlen(pDevInf->dbcc_name) - 4 >= MAX_PATH) return; + + StringCchCopyW(szDevId, MAX_PATH, pDevInf->dbcc_name + 4); + + // find last occurrence of '#' + wchar_t *idx = wcsrchr(szDevId, L'#'); + if(!idx) + { + szDevId[0] = L'\0'; + return; + } + + // truncate string at last '#' + *idx = L'\0'; + + // replace '#' with '\\' and convert string to upper case + for (wchar_t *p = szDevId; *p; ++p) + { + if (*p == L'#') + { + *p = L'\\'; + } + else + { + *p = towupper((unsigned)*p); + } + } +} static void SystemFavoritesServiceLogMessage (const wstring &errorMessage, WORD wType) { @@ -9128,13 +9744,168 @@ static void SystemFavoritesServiceSetStatus (DWORD status, DWORD waitHint = 0) SetServiceStatus (SystemFavoritesServiceStatusHandle, &SystemFavoritesServiceStatus); } +static void SystemFavoritesServiceUpdateLoaderProcessing (BOOL bForce) +{ + SystemFavoritesServiceLogInfo (L"SystemFavoritesServiceUpdateLoaderProcessing called"); + if (bForce || !(BootEncObj->ReadServiceConfigurationFlags () & VC_SYSTEM_FAVORITES_SERVICE_CONFIG_DONT_UPDATE_LOADER)) + { + SystemFavoritesServiceLogInfo (L"SystemFavoritesServiceUpdateLoaderProcessing processing"); + try + { + BootEncryption::UpdateSetupConfigFile (true); + SystemFavoritesServiceLogInfo (L"SystemFavoritesServiceUpdateLoaderProcessing: UpdateSetupConfigFile called"); + if (!BootEncStatus.HiddenSystem) + { + // re-install our bootloader again in case the update process has removed it. + bool bForceSetNextBoot = false; + bool bSetBootentry = true; + bool bForceFirstBootEntry = true; + bool bPostOOBE = true; + if (bForce) + bPostOOBE = false; + else + { + uint32 flags = BootEncObj->ReadServiceConfigurationFlags (); + if (flags & VC_SYSTEM_FAVORITES_SERVICE_CONFIG_FORCE_SET_BOOTNEXT) + bForceSetNextBoot = true; + if (flags & VC_SYSTEM_FAVORITES_SERVICE_CONFIG_DONT_SET_BOOTENTRY) + bSetBootentry = false; + if (flags & VC_SYSTEM_FAVORITES_SERVICE_CONFIG_DONT_FORCE_FIRST_BOOTENTRY) + bForceFirstBootEntry = false; + } + BootEncryption bootEnc (NULL, bPostOOBE, bSetBootentry, bForceFirstBootEntry, bForceSetNextBoot); + SystemFavoritesServiceLogInfo (L"SystemFavoritesServiceUpdateLoaderProcessing: InstallBootLoader calling"); + bootEnc.InstallBootLoader (true); + SystemFavoritesServiceLogInfo (L"SystemFavoritesServiceUpdateLoaderProcessing: InstallBootLoader called"); + } + } + catch (...) + { + } + } +} + +// Global vector containing all devices previsouly knwon to the system +std::vector<CDevice> g_Devices; -static VOID WINAPI SystemFavoritesServiceCtrlHandler (DWORD control) +static DWORD WINAPI SystemFavoritesServiceCtrlHandler ( DWORD dwControl, + DWORD dwEventType, + LPVOID lpEventData, + LPVOID lpContext) { - if (control == SERVICE_CONTROL_STOP) + switch (dwControl) + { + case SERVICE_CONTROL_PRESHUTDOWN: + case SERVICE_CONTROL_STOP: SystemFavoritesServiceSetStatus (SERVICE_STOP_PENDING); - else + + SystemFavoritesServiceUpdateLoaderProcessing (FALSE); + + /* clear VC_DRIVER_CONFIG_CLEAR_KEYS_ON_NEW_DEVICE_INSERTION flag */ + SetDriverConfigurationFlag (VC_DRIVER_CONFIG_CLEAR_KEYS_ON_NEW_DEVICE_INSERTION, FALSE); + SetEvent (SystemFavoriteServiceStopEvent); + SystemFavoritesServiceSetStatus (SERVICE_STOP_PENDING); + + break; + case SERVICE_CONTROL_POWEREVENT: + { + /* perform fixing of bootloader and SetupConfig.ini when the system resumes from sleep */ + if (dwEventType == PBT_APMRESUMEAUTOMATIC) + { + SystemFavoritesServiceUpdateLoaderProcessing (FALSE); + } + } + break; + case SERVICE_CONTROL_SESSIONCHANGE: + { + /* perform fixing of bootloader and SetupConfig.ini when the user logs in or when he unlocks his locked session */ + if ((dwEventType == WTS_SESSION_UNLOCK) || (dwEventType == WTS_SESSION_LOGON)) + { + SystemFavoritesServiceUpdateLoaderProcessing (FALSE); + } + } + break; + case VC_SERVICE_CONTROL_BUILD_DEVICE_LIST: + { + /* build a list of all devices currently connected to the system */ + /* ignore if clear keys configuration is already set */ + if (!(ReadDriverConfigurationFlags() & VC_DRIVER_CONFIG_CLEAR_KEYS_ON_NEW_DEVICE_INSERTION)) + { + SystemFavoritesServiceLogInfo (L"VC_SERVICE_CONTROL_BUILD_DEVICE_LIST received"); + g_Devices.clear (); + BuildDeviceList (g_Devices); + } + } + break; + case SERVICE_CONTROL_DEVICEEVENT: + if (DBT_DEVICEARRIVAL == dwEventType) + { + DEV_BROADCAST_HDR* pHdr = (DEV_BROADCAST_HDR *) lpEventData; + if (pHdr->dbch_devicetype != DBT_DEVTYP_VOLUME && pHdr->dbch_devicetype != DBT_DEVTYP_HANDLE) + { + if (ReadDriverConfigurationFlags() & VC_DRIVER_CONFIG_CLEAR_KEYS_ON_NEW_DEVICE_INSERTION) + { + BOOL bClearKeys = TRUE; + SystemFavoritesServiceLogInfo (L"SERVICE_CONTROL_DEVICEEVENT - DBT_DEVICEARRIVAL received"); + if (pHdr->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) + { + DEV_BROADCAST_DEVICEINTERFACE* pInf = (DEV_BROADCAST_DEVICEINTERFACE*) pHdr; + + if (IsEqualGUID (pInf->dbcc_classguid, OCL_GUID_DEVCLASS_SOFTWARECOMPONENT) + || IsEqualGUID (pInf->dbcc_classguid, GUID_DEVCLASS_VOLUME) + || IsEqualGUID (pInf->dbcc_classguid, GUID_DEVCLASS_VOLUMESNAPSHOT) + ) + { + bClearKeys = FALSE; + } + else + { + WCHAR szDevId[MAX_PATH]; + GetDeviceID(pInf, szDevId); + // device ID must contain "VID_" and "PID_" to be valid and it must not start with "SWD\" or "ROOT\" + if (wcsstr(szDevId, L"VID_") && wcsstr(szDevId, L"PID_") && wcsstr(szDevId, L"SWD\\") != szDevId && wcsstr(szDevId, L"ROOT\\") != szDevId) + { + CDevice dev(szDevId); + // look for the device in the list of devices already known to us and if it is there, then don't clear keys + if (std::find(g_Devices.begin(), g_Devices.end(), dev) != g_Devices.end()) + { + bClearKeys = FALSE; + } + else + { + // trace the device ID of the new device in the log + WCHAR szMsg[2*MAX_PATH]; + StringCbPrintfW(szMsg, sizeof(szMsg), L"SERVICE_CONTROL_DEVICEEVENT - New device ID: %s", szDevId); + SystemFavoritesServiceLogInfo (szMsg); + } + } + else + { + bClearKeys = FALSE; + } + } + } + + if (bClearKeys) + { + DWORD cbBytesReturned = 0; + + DeviceIoControl (hDriver, VC_IOCTL_EMERGENCY_CLEAR_ALL_KEYS, NULL, 0, NULL, 0, &cbBytesReturned, NULL); + } + else + { + SystemFavoritesServiceLogInfo (L"SERVICE_CONTROL_DEVICEEVENT - DBT_DEVICEARRIVAL ignored"); + } + } + } + } + break; + default: SystemFavoritesServiceSetStatus (SystemFavoritesServiceStatus.dwCurrentState); + break; + } + + return NO_ERROR; } static LONG WINAPI SystemFavoritesServiceExceptionHandler (EXCEPTION_POINTERS *ep) @@ -9156,44 +9927,91 @@ static void SystemFavoritesServiceInvalidParameterHandler (const wchar_t *expres static VOID WINAPI SystemFavoritesServiceMain (DWORD argc, LPTSTR *argv) { BOOL status = FALSE; + DEV_BROADCAST_DEVICEINTERFACE hdr; + BOOL bSkipMount = FALSE; + BOOL bUpdateLoader = FALSE; + DWORD i; memset (&SystemFavoritesServiceStatus, 0, sizeof (SystemFavoritesServiceStatus)); SystemFavoritesServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS; + SystemFavoritesServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP; + SystemFavoritesServiceStatus.dwControlsAccepted |= SERVICE_ACCEPT_PRESHUTDOWN | SERVICE_ACCEPT_SESSIONCHANGE | SERVICE_ACCEPT_POWEREVENT; + + for (i = 1; i < argc; i++) + { + if (0 == _wcsicmp (argv[i], VC_SYSTEM_FAVORITES_SERVICE_ARG_SKIP_MOUNT)) + bSkipMount = TRUE; + else if (0 == _wcsicmp (argv[i], VC_SYSTEM_FAVORITES_SERVICE_ARG_UPDATE_LOADER)) + bUpdateLoader = TRUE; + } + + ZeroMemory (&hdr, sizeof(hdr)); + hdr.dbcc_size = sizeof (hdr); + hdr.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; - SystemFavoritesServiceStatusHandle = RegisterServiceCtrlHandler (TC_SYSTEM_FAVORITES_SERVICE_NAME, SystemFavoritesServiceCtrlHandler); + SystemFavoritesServiceStatusHandle = RegisterServiceCtrlHandlerEx (TC_SYSTEM_FAVORITES_SERVICE_NAME, SystemFavoritesServiceCtrlHandler, NULL); if (!SystemFavoritesServiceStatusHandle) return; - InitGlobalLocks (); + SystemFavoriteServiceStopEvent = CreateEvent (NULL, FALSE, FALSE, NULL); + if (!SystemFavoriteServiceStopEvent) + return; + + SystemFavoriteServiceNotify = RegisterDeviceNotification (SystemFavoritesServiceStatusHandle, &hdr,DEVICE_NOTIFY_SERVICE_HANDLE | DEVICE_NOTIFY_ALL_INTERFACE_CLASSES); SetUnhandledExceptionFilter (SystemFavoritesServiceExceptionHandler); _set_invalid_parameter_handler (SystemFavoritesServiceInvalidParameterHandler); - SystemFavoritesServiceSetStatus (SERVICE_START_PENDING, 120000); - - SystemFavoritesServiceLogInfo (wstring (L"Initializing list of host devices")); - // initialize the list of devices available for mounting as early as possible - UpdateMountableHostDeviceList (); - - SystemFavoritesServiceLogInfo (wstring (L"Starting System Favorites mounting process")); - - try + if (bUpdateLoader) { - status = MountFavoriteVolumes (NULL, TRUE); + SystemFavoritesServiceSetStatus (SERVICE_START_PENDING, 120000); + SystemFavoritesServiceUpdateLoaderProcessing (TRUE); } - catch (...) { } - if (status) + if (!bSkipMount) { - SystemFavoritesServiceLogInfo (wstring (L"System Favorites mounting process finished")); + InitGlobalLocks (); + SystemFavoritesServiceSetStatus (SERVICE_START_PENDING, 120000); + + SystemFavoritesServiceLogInfo (wstring (L"Initializing list of host devices")); + + SystemFavoritesServiceLogInfo (wstring (L"Starting System Favorites mounting process")); + + try + { + status = MountFavoriteVolumes (NULL, TRUE); + } + catch (...) { } + + if (status) + { + SystemFavoritesServiceLogInfo (wstring (L"System Favorites mounting process finished")); + } + else + { + SystemFavoritesServiceLogError (wstring (L"System Favorites mounting process failed.")); + } + + FinalizeGlobalLocks (); + + if (!(ReadDriverConfigurationFlags() & TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD)) + WipeCache (NULL, TRUE); + + SystemFavoritesServiceUpdateLoaderProcessing (FALSE); } - else + + SystemFavoritesServiceSetStatus (SERVICE_RUNNING); + + WaitForSingleObject (SystemFavoriteServiceStopEvent, INFINITE); + + if (SystemFavoriteServiceNotify) { - SystemFavoritesServiceLogError (wstring (L"System Favorites mounting process failed.")); + UnregisterDeviceNotification (SystemFavoriteServiceNotify); + SystemFavoriteServiceNotify = NULL; } - FinalizeGlobalLocks (); + CloseHandle (SystemFavoriteServiceStopEvent); + SystemFavoriteServiceStopEvent = NULL; - SystemFavoritesServiceSetStatus (SERVICE_RUNNING); SystemFavoritesServiceSetStatus (SERVICE_STOPPED); } @@ -9206,12 +10024,24 @@ static BOOL StartSystemFavoritesService () bShowDisconnectedNetworkDrives = TRUE; bHideWaitingDialog = TRUE; bUseSecureDesktop = FALSE; + bUseLegacyMaxPasswordLength = FALSE; InitOSVersionInfo(); if (DriverAttach() != ERR_SUCCESS) return FALSE; + try + { + BootEncObj = new BootEncryption (NULL); + BootEncStatus = BootEncObj->GetStatus(); + bSystemIsGPT = BootEncObj->GetSystemDriveConfiguration().SystemPartition.IsGPT; + } + catch (Exception &) + { + BootEncStatus.DriveMounted = FALSE; + } + SERVICE_TABLE_ENTRY serviceTable[2]; serviceTable[0].lpServiceName = TC_SYSTEM_FAVORITES_SERVICE_NAME; serviceTable[0].lpServiceProc = SystemFavoritesServiceMain; @@ -9221,8 +10051,11 @@ static BOOL StartSystemFavoritesService () BOOL result = StartServiceCtrlDispatcher (serviceTable); - if (!(ReadDriverConfigurationFlags() & TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD)) - WipeCache (NULL, TRUE); + if (BootEncObj != NULL) + { + delete BootEncObj; + BootEncObj = NULL; + } return result; } @@ -9236,9 +10069,26 @@ int WINAPI wWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, wchar_t *lpsz if (argv && argc == 2 && wstring (TC_SYSTEM_FAVORITES_SERVICE_CMDLINE_OPTION) == argv[1]) return StartSystemFavoritesService() ? 0 : 1; + if (argv && argc == 2 && wstring (VC_WINDOWS_UPGRADE_POSTOOBE_CMDLINE_OPTION) == argv[1]) + { + InitOSVersionInfo(); + try + { + BootEncryption::UpdateSetupConfigFile (true); + // re-install our bootloader again in case the upgrade process has removed it. + BootEncryption bootEnc (NULL, true); + bootEnc.InstallBootLoader (true); + } + catch (...) + { + } + return 0; + } + int status; atexit (localcleanup); SetProcessShutdownParameters (0x100, 0); + DeobfuscateMagEndMarker (); VirtualLock (&VolumePassword, sizeof (VolumePassword)); VirtualLock (&CmdVolumePassword, sizeof (CmdVolumePassword)); @@ -9282,7 +10132,6 @@ int WINAPI wWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, wchar_t *lpsz DialogBoxParamW (hInstance, MAKEINTRESOURCEW (IDD_MOUNT_DLG), NULL, (DLGPROC) MainDialogProc, (LPARAM) lpszCommandLine); - FinalizeApp (); /* Terminate */ return 0; } @@ -9320,7 +10169,7 @@ BOOL TaskBarIconAdd (HWND hwnd) ScreenDPI >= 120 ? 0 : 16, (ScreenDPI >= 120 ? LR_DEFAULTSIZE : 0) | LR_SHARED - | (nCurrentOS != WIN_2000 ? LR_DEFAULTCOLOR : LR_VGACOLOR)); // Windows 2000 cannot display more than 16 fixed colors in notification tray + | LR_DEFAULTCOLOR); StringCbCopyW (tnid.szTip, sizeof(tnid.szTip), L"VeraCrypt"); @@ -9372,7 +10221,7 @@ BOOL TaskBarIconChange (HWND hwnd, int iconId) ScreenDPI >= 120 ? 0 : 16, (ScreenDPI >= 120 ? LR_DEFAULTSIZE : 0) | LR_SHARED - | (nCurrentOS != WIN_2000 ? LR_DEFAULTCOLOR : LR_VGACOLOR)); // Windows 2000 cannot display more than 16 fixed colors in notification tray + | LR_DEFAULTCOLOR); return Shell_NotifyIcon (NIM_MODIFY, &tnid); } @@ -9435,7 +10284,7 @@ void DismountIdleVolumes () if (bWipeCacheOnAutoDismount) { DeviceIoControl (hDriver, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0, &dwResult, NULL); - SecurityToken::CloseAllSessions(); + SecurityToken::CloseAllSessions(); // TODO Use Token } } } @@ -9531,7 +10380,7 @@ static BOOL MountFavoriteVolumeBase (HWND hwnd, const FavoriteVolume &favorite, else mountOptions.ProtectedHidVolPkcs5Prf = CmdVolumePkcs5; mountOptions.ProtectedHidVolPim = CmdVolumePim; - if (DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_MOUNT_OPTIONS), hwnd, (DLGPROC) MountOptionsDlgProc, (LPARAM) &mountOptions) == IDCANCEL) + if (Silent || (SecureDesktopDialogBoxParam (hInst, MAKEINTRESOURCEW (IDD_MOUNT_OPTIONS), hwnd, (DLGPROC) MountOptionsDlgProc, (LPARAM) &mountOptions) == IDCANCEL)) { status = FALSE; goto skipMount; @@ -9543,7 +10392,7 @@ static BOOL MountFavoriteVolumeBase (HWND hwnd, const FavoriteVolume &favorite, if (ServiceMode) SystemFavoritesServiceLogInfo (wstring (L"Mounting system favorite \"") + effectiveVolumePath + L"\""); - status = Mount (hwnd, drive, (wchar_t *) effectiveVolumePath.c_str(), favorite.Pim, favorite.Pkcs5, favorite.TrueCryptMode); + status = Mount (hwnd, drive, (wchar_t *) effectiveVolumePath.c_str(), favorite.Pim, favorite.Pkcs5); if (ServiceMode) { @@ -9619,6 +10468,7 @@ BOOL MountFavoriteVolumes (HWND hwnd, BOOL systemFavorites, BOOL logOnMount, BOO } mountOptions = defaultMountOptions; + mountOptions.SkipCachedPasswords = FALSE; VolumePassword.Length = 0; MultipleMountOperationInProgress = (favoriteVolumeToMount.Path.empty() || FavoriteMountOnArrivalInProgress); @@ -9705,9 +10555,6 @@ BOOL MountFavoriteVolumes (HWND hwnd, BOOL systemFavorites, BOOL logOnMount, BOO { Sleep (5000); - SystemFavoritesServiceLogInfo (wstring (L"Updating list of host devices")); - UpdateMountableHostDeviceList (); - SystemFavoritesServiceLogInfo (wstring (L"Trying to mount skipped system favorites")); // Update the service status to avoid being killed @@ -9763,10 +10610,9 @@ BOOL MountFavoriteVolumes (HWND hwnd, BOOL systemFavorites, BOOL logOnMount, BOO burn (&VolumePassword, sizeof (VolumePassword)); burn (&VolumePkcs5, sizeof (VolumePkcs5)); burn (&VolumePim, sizeof (VolumePim)); - burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); if (bRet && CloseSecurityTokenSessionsAfterMount) - SecurityToken::CloseAllSessions(); + SecurityToken::CloseAllSessions(); // TODO Use Token return bRet; } @@ -9791,6 +10637,7 @@ void CALLBACK mountFavoriteVolumeCallbackFunction (void *pArg, HWND hwnd) void __cdecl mountFavoriteVolumeThreadFunction (void *pArg) { ShowWaitDialog (MainDlg, FALSE, mountFavoriteVolumeCallbackFunction, pArg); + _InterlockedExchange(&FavoriteMountOnGoing, 0); } static void SaveDefaultKeyFilesParam (HWND hwnd) @@ -9919,19 +10766,22 @@ static void HandleHotKey (HWND hwndDlg, WPARAM wParam) MessageBeep (0xFFFFFFFF); } TaskBarIconRemove (hwndDlg); - UnregisterWtsNotification(hwndDlg); + UnregisterWtsAndPowerNotification(hwndDlg); EndMainDlg (hwndDlg); break; case HK_MOUNT_FAVORITE_VOLUMES: { - mountFavoriteVolumeThreadParam* pParam = (mountFavoriteVolumeThreadParam*) calloc(1, sizeof(mountFavoriteVolumeThreadParam)); - pParam->systemFavorites = FALSE; - pParam->logOnMount = FALSE; - pParam->hotKeyMount = TRUE; - pParam->favoriteVolumeToMount = NULL; + if (0 == _InterlockedCompareExchange(&FavoriteMountOnGoing, 1, 0)) + { + mountFavoriteVolumeThreadParam* pParam = (mountFavoriteVolumeThreadParam*) calloc(1, sizeof(mountFavoriteVolumeThreadParam)); + pParam->systemFavorites = FALSE; + pParam->logOnMount = FALSE; + pParam->hotKeyMount = TRUE; + pParam->favoriteVolumeToMount = NULL; - _beginthread(mountFavoriteVolumeThreadFunction, 0, pParam); + _beginthread(mountFavoriteVolumeThreadFunction, 0, pParam); + } } break; @@ -9940,7 +10790,7 @@ static void HandleHotKey (HWND hwndDlg, WPARAM wParam) break; case HK_CLOSE_SECURITY_TOKEN_SESSIONS: - SecurityToken::CloseAllSessions(); + SecurityToken::CloseAllSessions(); // TODO Use Token InfoBalloon (NULL, "ALL_TOKEN_SESSIONS_CLOSED", hwndDlg); @@ -10032,7 +10882,7 @@ int BackupVolumeHeader (HWND hwndDlg, BOOL bRequireConfirmation, const wchar_t * { int GuiPkcs5 = ((EffectiveVolumePkcs5 > 0) && (*askPkcs5 == 0))? EffectiveVolumePkcs5 : *askPkcs5; int GuiPim = ((EffectiveVolumePim > 0) && (*askPim <= 0))? EffectiveVolumePim : *askPim; - if (!AskVolumePassword (hwndDlg, askPassword, &GuiPkcs5, &GuiPim, &VolumeTrueCryptMode, type == TC_VOLUME_TYPE_HIDDEN ? "ENTER_HIDDEN_VOL_PASSWORD" : "ENTER_NORMAL_VOL_PASSWORD", FALSE)) + if (!AskVolumePassword (hwndDlg, askPassword, &GuiPkcs5, &GuiPim, type == TC_VOLUME_TYPE_HIDDEN ? "ENTER_HIDDEN_VOL_PASSWORD" : "ENTER_NORMAL_VOL_PASSWORD", FALSE)) { nStatus = ERR_SUCCESS; goto ret; @@ -10050,7 +10900,7 @@ int BackupVolumeHeader (HWND hwndDlg, BOOL bRequireConfirmation, const wchar_t * if (KeyFilesEnable && FirstKeyFile) KeyFilesApply (hwndDlg, askPassword, FirstKeyFile, lpszVolume); - nStatus = OpenVolume (askVol, lpszVolume, askPassword, *askPkcs5, *askPim, VolumeTrueCryptMode, FALSE, bPreserveTimestamp, FALSE); + nStatus = OpenVolume (askVol, lpszVolume, askPassword, *askPkcs5, *askPim, FALSE, bPreserveTimestamp, FALSE); NormalCursor(); @@ -10107,7 +10957,7 @@ noHidden: goto ret; /* Select backup file */ - if (!BrowseFiles (hwndDlg, "OPEN_TITLE", szFileName, bHistory, TRUE, NULL)) + if (!BrowseFiles (hwndDlg, "OPEN_TITLE", szFileName, bHistory, TRUE)) goto ret; /* Conceive the backup file */ @@ -10151,7 +11001,7 @@ noHidden: goto error; } - if (EAInit (volume.CryptoInfo->ea, temporaryKey, volume.CryptoInfo->ks) != ERR_SUCCESS || !EAInitMode (volume.CryptoInfo)) + if (EAInit (volume.CryptoInfo->ea, temporaryKey, volume.CryptoInfo->ks) != ERR_SUCCESS || !EAInitMode (volume.CryptoInfo, volume.CryptoInfo->k2)) { nStatus = ERR_PARAMETER_INCORRECT; goto error; @@ -10160,7 +11010,7 @@ noHidden: EncryptBuffer (backup, backupFileSize, volume.CryptoInfo); memcpy (volume.CryptoInfo->k2, originalK2, sizeof (volume.CryptoInfo->k2)); - if (EAInit (volume.CryptoInfo->ea, volume.CryptoInfo->master_keydata, volume.CryptoInfo->ks) != ERR_SUCCESS || !EAInitMode (volume.CryptoInfo)) + if (EAInit (volume.CryptoInfo->ea, volume.CryptoInfo->master_keydata, volume.CryptoInfo->ks) != ERR_SUCCESS || !EAInitMode (volume.CryptoInfo, volume.CryptoInfo->k2)) { nStatus = ERR_PARAMETER_INCORRECT; goto error; @@ -10208,7 +11058,6 @@ error: burn (&VolumePassword, sizeof (VolumePassword)); burn (&VolumePkcs5, sizeof (VolumePkcs5)); burn (&VolumePim, sizeof (VolumePim)); - burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); burn (&hiddenVolPassword, sizeof (hiddenVolPassword)); burn (temporaryKey, sizeof (temporaryKey)); burn (originalK2, sizeof (originalK2)); @@ -10320,7 +11169,7 @@ int RestoreVolumeHeader (HWND hwndDlg, const wchar_t *lpszVolume) int GuiPkcs5 = ((EffectiveVolumePkcs5 > 0) && (VolumePkcs5 == 0))? EffectiveVolumePkcs5 : VolumePkcs5; int GuiPim = ((EffectiveVolumePim > 0) && (VolumePim <= 0))? EffectiveVolumePim : VolumePim; StringCbCopyW (PasswordDlgVolume, sizeof(PasswordDlgVolume), lpszVolume); - if (!AskVolumePassword (hwndDlg, &VolumePassword, &GuiPkcs5, &GuiPim, &VolumeTrueCryptMode, NULL, FALSE)) + if (!AskVolumePassword (hwndDlg, &VolumePassword, &GuiPkcs5, &GuiPim, NULL, FALSE)) { nStatus = ERR_SUCCESS; goto ret; @@ -10338,7 +11187,7 @@ int RestoreVolumeHeader (HWND hwndDlg, const wchar_t *lpszVolume) if (KeyFilesEnable && FirstKeyFile) KeyFilesApply (hwndDlg, &VolumePassword, FirstKeyFile, lpszVolume); - nStatus = OpenVolume (&volume, lpszVolume, &VolumePassword, VolumePkcs5, VolumePim, VolumeTrueCryptMode,TRUE, bPreserveTimestamp, TRUE); + nStatus = OpenVolume (&volume, lpszVolume, &VolumePassword, VolumePkcs5, VolumePim,TRUE, bPreserveTimestamp, TRUE); NormalCursor(); @@ -10391,7 +11240,7 @@ int RestoreVolumeHeader (HWND hwndDlg, const wchar_t *lpszVolume) } /* Select backup file */ - if (!BrowseFiles (hwndDlg, "OPEN_TITLE", szFileName, bHistory, FALSE, NULL)) + if (!BrowseFiles (hwndDlg, "OPEN_TITLE", szFileName, bHistory, FALSE)) { nStatus = ERR_SUCCESS; goto ret; @@ -10432,6 +11281,21 @@ int RestoreVolumeHeader (HWND hwndDlg, const wchar_t *lpszVolume) nStatus = ERR_OS_ERROR; goto error; } + else if (!bDevice && bPreserveTimestamp) + { + // ensure that Last Access timestamp is not modified + ftLastAccessTime.dwHighDateTime = 0xFFFFFFFF; + ftLastAccessTime.dwLowDateTime = 0xFFFFFFFF; + + SetFileTime (dev, NULL, &ftLastAccessTime, NULL); + + /* Remember the container modification/creation date and time. */ + + if (GetFileTime ((HANDLE) dev, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime) == 0) + bTimeStampValid = FALSE; + else + bTimeStampValid = TRUE; + } // Determine volume host size if (bDevice) @@ -10454,9 +11318,34 @@ int RestoreVolumeHeader (HWND hwndDlg, const wchar_t *lpszVolume) dgBuffer, sizeof (dgBuffer), &dwResult, NULL); if (!bResult) - goto error; + { + DISK_GEOMETRY geo; + if (DeviceIoControl (dev, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, (LPVOID) &geo, sizeof (geo), &dwResult, NULL)) + { + hostSize = geo.Cylinders.QuadPart * geo.SectorsPerTrack * geo.TracksPerCylinder * geo.BytesPerSector; - hostSize = ((PDISK_GEOMETRY_EX) dgBuffer)->DiskSize.QuadPart; + if (CurrentOSMajor >= 6) + { + STORAGE_READ_CAPACITY storage = {0}; + + storage.Version = sizeof (STORAGE_READ_CAPACITY); + storage.Size = sizeof (STORAGE_READ_CAPACITY); + if (DeviceIoControl (dev, IOCTL_STORAGE_READ_CAPACITY, NULL, 0, (LPVOID) &storage, sizeof (storage), &dwResult, NULL) + && (dwResult >= sizeof (storage)) + && (storage.Size == sizeof (STORAGE_READ_CAPACITY)) + ) + { + hostSize = storage.DiskLength.QuadPart; + } + } + } + else + { + goto error; + } + } + else + hostSize = ((PDISK_GEOMETRY_EX) dgBuffer)->DiskSize.QuadPart; } if (hostSize == 0) @@ -10477,15 +11366,6 @@ int RestoreVolumeHeader (HWND hwndDlg, const wchar_t *lpszVolume) hostSize = fileSize.QuadPart; } - if (!bDevice && bPreserveTimestamp) - { - /* Remember the container modification/creation date and time. */ - - if (GetFileTime ((HANDLE) dev, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime) == 0) - bTimeStampValid = FALSE; - else - bTimeStampValid = TRUE; - } /* Read the volume header from the backup file */ char buffer[TC_VOLUME_HEADER_GROUP_SIZE]; @@ -10530,7 +11410,7 @@ int RestoreVolumeHeader (HWND hwndDlg, const wchar_t *lpszVolume) { int GuiPkcs5 = ((EffectiveVolumePkcs5 > 0) && (VolumePkcs5 == 0))? EffectiveVolumePkcs5 : VolumePkcs5; int GuiPim = ((EffectiveVolumePim > 0) && (VolumePim <= 0))? EffectiveVolumePim : VolumePim; - if (!AskVolumePassword (hwndDlg, &VolumePassword, &GuiPkcs5, &GuiPim, &VolumeTrueCryptMode, "ENTER_HEADER_BACKUP_PASSWORD", FALSE)) + if (!AskVolumePassword (hwndDlg, &VolumePassword, &GuiPkcs5, &GuiPim, "ENTER_HEADER_BACKUP_PASSWORD", FALSE)) { nStatus = ERR_SUCCESS; goto ret; @@ -10553,7 +11433,7 @@ int RestoreVolumeHeader (HWND hwndDlg, const wchar_t *lpszVolume) if (type == TC_VOLUME_TYPE_HIDDEN) headerOffsetBackupFile += (legacyBackup ? TC_VOLUME_HEADER_SIZE_LEGACY : TC_VOLUME_HEADER_SIZE); - nStatus = ReadVolumeHeader (FALSE, buffer + headerOffsetBackupFile, &VolumePassword, VolumePkcs5, VolumePim, VolumeTrueCryptMode, &restoredCryptoInfo, NULL); + nStatus = ReadVolumeHeader (FALSE, buffer + headerOffsetBackupFile, &VolumePassword, VolumePkcs5, VolumePim, &restoredCryptoInfo, NULL); if (nStatus == ERR_SUCCESS) break; } @@ -10659,7 +11539,6 @@ error: burn (&VolumePassword, sizeof (VolumePassword)); burn (&VolumePkcs5, sizeof (VolumePkcs5)); burn (&VolumePim, sizeof (VolumePim)); - burn (&VolumeTrueCryptMode, sizeof (VolumeTrueCryptMode)); RestoreDefaultKeyFilesParam(); RandStop (FALSE); NormalCursor(); @@ -10670,12 +11549,32 @@ error: void SetDriverConfigurationFlag (uint32 flag, BOOL state) { - BootEncObj->SetDriverConfigurationFlag (flag, state ? true : false); + if (BootEncObj) + BootEncObj->SetDriverConfigurationFlag (flag, state ? true : false); } +void SetServiceConfigurationFlag (uint32 flag, BOOL state) +{ + if (BootEncObj) + BootEncObj->SetServiceConfigurationFlag (flag, state ? true : false); +} + +void SetMemoryProtectionConfig (BOOL bEnable) +{ + DWORD config = bEnable? 1: 0; + if (BootEncObj) + BootEncObj->WriteLocalMachineRegistryDwordValue (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", VC_ENABLE_MEMORY_PROTECTION, config); +} + +void NotifyService (DWORD dwNotifyCmd) +{ + if (BootEncObj) + BootEncObj->NotifyService (dwNotifyCmd); +} static BOOL CALLBACK PerformanceSettingsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) { + static HWND hDisableMemProtectionTooltipWnd = NULL; WORD lw = LOWORD (wParam); switch (msg) @@ -10687,27 +11586,59 @@ static BOOL CALLBACK PerformanceSettingsDlgProc (HWND hwndDlg, UINT msg, WPARAM uint32 driverConfig = ReadDriverConfigurationFlags(); CheckDlgButton (hwndDlg, IDC_ENABLE_HARDWARE_ENCRYPTION, (driverConfig & TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION) ? BST_UNCHECKED : BST_CHECKED); CheckDlgButton (hwndDlg, IDC_ENABLE_EXTENDED_IOCTL_SUPPORT, (driverConfig & TC_DRIVER_CONFIG_ENABLE_EXTENDED_IOCTL) ? BST_CHECKED : BST_UNCHECKED); + CheckDlgButton (hwndDlg, IDC_ALLOW_TRIM_NONSYS_SSD, (driverConfig & VC_DRIVER_CONFIG_ALLOW_NONSYS_TRIM) ? BST_CHECKED : BST_UNCHECKED); + // checkbox for Windows Defragmenter only usuable starting from Windows 8.1 + // on previous versions, we can not control Windows defragmenter so + // this settings is always checked. + if (IsOSAtLeast (WIN_8_1)) + CheckDlgButton (hwndDlg, IDC_ALLOW_WINDOWS_DEFRAG, (driverConfig & VC_DRIVER_CONFIG_ALLOW_WINDOWS_DEFRAG) ? BST_CHECKED : BST_UNCHECKED); + else + { + CheckDlgButton (hwndDlg, IDC_ALLOW_WINDOWS_DEFRAG, BST_CHECKED); + EnableWindow (GetDlgItem (hwndDlg, IDC_ALLOW_WINDOWS_DEFRAG), FALSE); + } + + if (IsCpuRngSupported()) + { + CheckDlgButton (hwndDlg, IDC_ENABLE_CPU_RNG, (driverConfig & VC_DRIVER_CONFIG_ENABLE_CPU_RNG) ? BST_CHECKED : BST_UNCHECKED); + } + else + { + CheckDlgButton (hwndDlg, IDC_ENABLE_CPU_RNG, BST_UNCHECKED); + EnableWindow (GetDlgItem (hwndDlg, IDC_ENABLE_CPU_RNG), FALSE); + } + + if (IsRamEncryptionSupported()) + { + CheckDlgButton (hwndDlg, IDC_ENABLE_RAM_ENCRYPTION, (driverConfig & VC_DRIVER_CONFIG_ENABLE_RAM_ENCRYPTION) ? BST_CHECKED : BST_UNCHECKED); + } + else + { + CheckDlgButton (hwndDlg, IDC_ENABLE_RAM_ENCRYPTION, BST_UNCHECKED); + EnableWindow (GetDlgItem (hwndDlg, IDC_ENABLE_RAM_ENCRYPTION), FALSE); + } - SYSTEM_INFO sysInfo; - GetSystemInfo (&sysInfo); + CheckDlgButton (hwndDlg, IDC_DISABLE_MEMORY_PROTECTION, ReadMemoryProtectionConfig() ? BST_UNCHECKED : BST_CHECKED); + + size_t cpuCount = GetCpuCount(NULL); HWND freeCpuCombo = GetDlgItem (hwndDlg, IDC_ENCRYPTION_FREE_CPU_COUNT); uint32 encryptionFreeCpuCount = ReadEncryptionThreadPoolFreeCpuCountLimit(); - if (encryptionFreeCpuCount > sysInfo.dwNumberOfProcessors - 1) - encryptionFreeCpuCount = sysInfo.dwNumberOfProcessors - 1; + if (encryptionFreeCpuCount > (uint32) (cpuCount - 1)) + encryptionFreeCpuCount = (uint32) (cpuCount - 1); - for (uint32 i = 1; i < sysInfo.dwNumberOfProcessors; ++i) + for (uint32 i = 1; i < cpuCount; ++i) { wstringstream s; s << i; AddComboPair (freeCpuCombo, s.str().c_str(), i); } - if (sysInfo.dwNumberOfProcessors < 2 || encryptionFreeCpuCount == 0) + if (cpuCount < 2 || encryptionFreeCpuCount == 0) EnableWindow (freeCpuCombo, FALSE); - if (sysInfo.dwNumberOfProcessors < 2) + if (cpuCount < 2) EnableWindow (GetDlgItem (hwndDlg, IDC_LIMIT_ENC_THREAD_POOL), FALSE); if (encryptionFreeCpuCount != 0) @@ -10718,13 +11649,28 @@ static BOOL CALLBACK PerformanceSettingsDlgProc (HWND hwndDlg, UINT msg, WPARAM SetWindowTextW (GetDlgItem (hwndDlg, IDT_LIMIT_ENC_THREAD_POOL_NOTE), GetString("LIMIT_ENC_THREAD_POOL_NOTE")); - SetDlgItemTextW (hwndDlg, IDC_HW_AES_SUPPORTED_BY_CPU, (wstring (L" ") + (GetString (is_aes_hw_cpu_supported() ? "UISTR_YES" : "UISTR_NO"))).c_str()); + SetDlgItemTextW (hwndDlg, IDC_HW_AES_SUPPORTED_BY_CPU, (wstring (L" ") + (GetString (HasAESNI() ? "UISTR_YES" : "UISTR_NO"))).c_str()); ToHyperlink (hwndDlg, IDC_MORE_INFO_ON_HW_ACCELERATION); ToHyperlink (hwndDlg, IDC_MORE_INFO_ON_THREAD_BASED_PARALLELIZATION); + + hDisableMemProtectionTooltipWnd = CreateToolTip (IDC_DISABLE_MEMORY_PROTECTION, hwndDlg, "DISABLE_MEMORY_PROTECTION_WARNING"); + // make IDC_DISABLE_MEMORY_PROTECTION control fit the text so that the tooltip is shown only when mouse is over the text + AccommodateCheckBoxTextWidth(hwndDlg, IDC_DISABLE_MEMORY_PROTECTION); + // make the help button adjacent to the checkbox + MakeControlsContiguous(hwndDlg, IDC_DISABLE_MEMORY_PROTECTION, IDC_DISABLE_MEMORY_PROTECTION_HELP); } return 0; + // handle message to destroy hDisableMemProtectionTooltipWnd when the dialog is closed + case WM_DESTROY: + if (hDisableMemProtectionTooltipWnd) + { + DestroyWindow (hDisableMemProtectionTooltipWnd); + hDisableMemProtectionTooltipWnd = NULL; + } + break; + case WM_COMMAND: switch (lw) @@ -10743,11 +11689,19 @@ static BOOL CALLBACK PerformanceSettingsDlgProc (HWND hwndDlg, UINT msg, WPARAM } BOOL disableHW = !IsDlgButtonChecked (hwndDlg, IDC_ENABLE_HARDWARE_ENCRYPTION); + BOOL enableCpuRng = IsDlgButtonChecked (hwndDlg, IDC_ENABLE_CPU_RNG); + BOOL enableRamEncryption = IsDlgButtonChecked (hwndDlg, IDC_ENABLE_RAM_ENCRYPTION); BOOL enableExtendedIOCTL = IsDlgButtonChecked (hwndDlg, IDC_ENABLE_EXTENDED_IOCTL_SUPPORT); + BOOL allowTrimCommand = IsDlgButtonChecked (hwndDlg, IDC_ALLOW_TRIM_NONSYS_SSD); + BOOL allowWindowsDefrag = IsDlgButtonChecked (hwndDlg, IDC_ALLOW_WINDOWS_DEFRAG); + BOOL bDisableMemoryProtection = IsDlgButtonChecked (hwndDlg, IDC_DISABLE_MEMORY_PROTECTION); try { VOLUME_PROPERTIES_STRUCT prop; + bool rebootRequired = false; + uint32 driverConfig = ReadDriverConfigurationFlags(); + try { BootEncStatus = BootEncObj->GetStatus(); @@ -10780,12 +11734,46 @@ static BOOL CALLBACK PerformanceSettingsDlgProc (HWND hwndDlg, UINT msg, WPARAM SetDriverConfigurationFlag (TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION, disableHW); SetDriverConfigurationFlag (TC_DRIVER_CONFIG_ENABLE_EXTENDED_IOCTL, enableExtendedIOCTL); + SetDriverConfigurationFlag (VC_DRIVER_CONFIG_ALLOW_NONSYS_TRIM, allowTrimCommand); + if (IsOSAtLeast (WIN_8_1)) + SetDriverConfigurationFlag (VC_DRIVER_CONFIG_ALLOW_WINDOWS_DEFRAG, allowWindowsDefrag); + SetDriverConfigurationFlag (VC_DRIVER_CONFIG_ENABLE_CPU_RNG, enableCpuRng); + + BOOL originalRamEncryptionEnabled = (driverConfig & VC_DRIVER_CONFIG_ENABLE_RAM_ENCRYPTION)? TRUE : FALSE; + if (originalRamEncryptionEnabled != enableRamEncryption) + { + if (enableRamEncryption) + { + // Disable Hibernate and Fast Startup if they are enabled + BOOL bHibernateEnabled, bHiberbootEnabled; + if (GetHibernateStatus (bHibernateEnabled, bHiberbootEnabled)) + { + if (bHibernateEnabled) + { + BootEncObj->WriteLocalMachineRegistryDwordValue (L"SYSTEM\\CurrentControlSet\\Control\\Power", L"HibernateEnabled", 0); + } + + if (bHiberbootEnabled) + { + BootEncObj->WriteLocalMachineRegistryDwordValue (L"SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Power", L"HiberbootEnabled", 0); + } + } + } + rebootRequired = true; + } + SetDriverConfigurationFlag (VC_DRIVER_CONFIG_ENABLE_RAM_ENCRYPTION, enableRamEncryption); + + BOOL originalDisableMemoryProtection = !ReadMemoryProtectionConfig(); + if(originalDisableMemoryProtection != bDisableMemoryProtection) + rebootRequired = true; + SetMemoryProtectionConfig (!bDisableMemoryProtection); DWORD bytesReturned; if (!DeviceIoControl (hDriver, TC_IOCTL_REREAD_DRIVER_CONFIG, NULL, 0, NULL, 0, &bytesReturned, NULL)) handleWin32Error (hwndDlg, SRC_POS); EnableHwEncryption (!disableHW); + EnableCpuRng (enableCpuRng); uint32 cpuFreeCount = 0; if (IsDlgButtonChecked (hwndDlg, IDC_LIMIT_ENC_THREAD_POOL)) @@ -10798,9 +11786,12 @@ static BOOL CALLBACK PerformanceSettingsDlgProc (HWND hwndDlg, UINT msg, WPARAM if (ReadEncryptionThreadPoolFreeCpuCountLimit() != cpuFreeCount) { BootEncObj->WriteLocalMachineRegistryDwordValue (L"SYSTEM\\CurrentControlSet\\Services\\veracrypt", TC_ENCRYPTION_FREE_CPU_COUNT_REG_VALUE_NAME, cpuFreeCount); - Warning ("SETTING_REQUIRES_REBOOT", hwndDlg); + rebootRequired = true; } + if (rebootRequired) + Warning ("SETTING_REQUIRES_REBOOT", hwndDlg); + EndDialog (hwndDlg, lw); return 1; } @@ -10811,6 +11802,14 @@ static BOOL CALLBACK PerformanceSettingsDlgProc (HWND hwndDlg, UINT msg, WPARAM } return 1; + case IDC_ALLOW_WINDOWS_DEFRAG: + if (IsDlgButtonChecked (hwndDlg, IDC_ALLOW_WINDOWS_DEFRAG) + && AskWarnYesNo ("CONFIRM_ALLOW_WINDOWS_DEFRAG", hwndDlg) == IDNO) + { + CheckDlgButton (hwndDlg, IDC_ALLOW_WINDOWS_DEFRAG, BST_UNCHECKED); + } + return 1; + case IDC_ENABLE_HARDWARE_ENCRYPTION: if (!IsDlgButtonChecked (hwndDlg, IDC_ENABLE_HARDWARE_ENCRYPTION) && AskWarnYesNo ("CONFIRM_SETTING_DEGRADES_PERFORMANCE", hwndDlg) == IDNO) @@ -10834,6 +11833,53 @@ static BOOL CALLBACK PerformanceSettingsDlgProc (HWND hwndDlg, UINT msg, WPARAM EnableWindow (GetDlgItem (hwndDlg, IDC_ENCRYPTION_FREE_CPU_COUNT), IsDlgButtonChecked (hwndDlg, IDC_LIMIT_ENC_THREAD_POOL)); return 1; + case IDC_ENABLE_RAM_ENCRYPTION: + { + uint32 driverConfig = ReadDriverConfigurationFlags(); + BOOL originalRamEncryptionEnabled = (driverConfig & VC_DRIVER_CONFIG_ENABLE_RAM_ENCRYPTION)? TRUE : FALSE; + BOOL enableRamEncryption = IsDlgButtonChecked (hwndDlg, IDC_ENABLE_RAM_ENCRYPTION); + + if (originalRamEncryptionEnabled != enableRamEncryption) + { + if (enableRamEncryption) + { + // check if Hibernate or Fast Startup are enabled + BOOL bHibernateEnabled, bHiberbootEnabled; + if (GetHibernateStatus (bHibernateEnabled, bHiberbootEnabled)) + { + if (bHibernateEnabled || bHiberbootEnabled) + { + if (AskWarnYesNo ("RAM_ENCRYPTION_DISABLE_HIBERNATE", hwndDlg) == IDNO) + { + CheckDlgButton (hwndDlg, IDC_ENABLE_RAM_ENCRYPTION, BST_UNCHECKED); + return 1; + } + } + } + } + Warning ("SETTING_REQUIRES_REBOOT", hwndDlg); + } + } + return 1; + + case IDC_DISABLE_MEMORY_PROTECTION: + { + BOOL disableMemoryProtection = IsDlgButtonChecked (hwndDlg, IDC_DISABLE_MEMORY_PROTECTION); + BOOL originalDisableMemoryProtection = !ReadMemoryProtectionConfig(); + if (disableMemoryProtection != originalDisableMemoryProtection) + { + if (disableMemoryProtection) + { + Warning ("DISABLE_MEMORY_PROTECTION_WARNING", hwndDlg); + } + + Warning ("SETTING_REQUIRES_REBOOT", hwndDlg); + } + } + return 1; + case IDC_DISABLE_MEMORY_PROTECTION_HELP: + Applink ("memoryprotection"); + return 1; case IDC_BENCHMARK: Benchmark (hwndDlg); return 1; @@ -10864,6 +11910,7 @@ static BOOL CALLBACK SecurityTokenPreferencesDlgProc (HWND hwndDlg, UINT msg, WP LocalizeDialog (hwndDlg, "IDD_TOKEN_PREFERENCES"); SetDlgItemText (hwndDlg, IDC_PKCS11_MODULE, SecurityTokenLibraryPath); CheckDlgButton (hwndDlg, IDC_CLOSE_TOKEN_SESSION_AFTER_MOUNT, CloseSecurityTokenSessionsAfterMount ? BST_CHECKED : BST_UNCHECKED); + CheckDlgButton (hwndDlg, IDC_ENABLE_EMV_SUPPORT, EMVSupportEnabled ? BST_CHECKED : BST_UNCHECKED); SetWindowTextW (GetDlgItem (hwndDlg, IDT_PKCS11_LIB_HELP), GetString("PKCS11_LIB_LOCATION_HELP")); @@ -10886,7 +11933,7 @@ static BOOL CALLBACK SecurityTokenPreferencesDlgProc (HWND hwndDlg, UINT msg, WP { try { - SecurityToken::CloseLibrary(); + SecurityToken::CloseLibrary(); // TODO Use Token } catch (...) { } @@ -10906,7 +11953,7 @@ static BOOL CALLBACK SecurityTokenPreferencesDlgProc (HWND hwndDlg, UINT msg, WP } CloseSecurityTokenSessionsAfterMount = (IsDlgButtonChecked (hwndDlg, IDC_CLOSE_TOKEN_SESSION_AFTER_MOUNT) == BST_CHECKED); - + EMVSupportEnabled = (IsDlgButtonChecked (hwndDlg, IDC_ENABLE_EMV_SUPPORT) == BST_CHECKED); WaitCursor (); SaveSettings (hwndDlg); NormalCursor (); @@ -11010,9 +12057,6 @@ static BOOL CALLBACK DefaultMountParametersDlgProc (HWND hwndDlg, UINT msg, WPAR { LocalizeDialog (hwndDlg, "IDD_DEFAULT_MOUNT_PARAMETERS"); - SendMessage (GetDlgItem (hwndDlg, IDC_TRUECRYPT_MODE), BM_SETCHECK, - DefaultVolumeTrueCryptMode ? BST_CHECKED:BST_UNCHECKED, 0); - /* Populate the PRF algorithms list */ int i, nIndex, defaultPrfIndex = 0; HWND hComboBox = GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID); @@ -11046,25 +12090,14 @@ static BOOL CALLBACK DefaultMountParametersDlgProc (HWND hwndDlg, UINT msg, WPAR case IDOK: { int pkcs5 = (int) SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETITEMDATA, SendMessage (GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID), CB_GETCURSEL, 0, 0), 0); - BOOL truecryptMode = GetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE); - /* check that PRF is supported in TrueCrypt Mode */ - if ( (truecryptMode) - && (!is_pkcs5_prf_supported(pkcs5, TRUE, PRF_BOOT_NO)) - ) - { - Error ("ALGO_NOT_SUPPORTED_FOR_TRUECRYPT_MODE", hwndDlg); - } - else - { - WaitCursor (); - DefaultVolumeTrueCryptMode = truecryptMode; - DefaultVolumePkcs5 = pkcs5; - SaveSettings (hwndDlg); + WaitCursor (); + DefaultVolumePkcs5 = pkcs5; - NormalCursor (); - EndDialog (hwndDlg, lw); - } + SaveSettings (hwndDlg); + + NormalCursor (); + EndDialog (hwndDlg, lw); return 1; } @@ -11084,6 +12117,8 @@ static BOOL CALLBACK BootLoaderPreferencesDlgProc (HWND hwndDlg, UINT msg, WPARA { WORD lw = LOWORD (wParam); static std::string platforminfo; + static byte currentUserConfig; + static string currentCustomUserMessage; switch (msg) { @@ -11101,11 +12136,34 @@ static BOOL CALLBACK BootLoaderPreferencesDlgProc (HWND hwndDlg, UINT msg, WPARA { LocalizeDialog (hwndDlg, "IDD_SYSENC_SETTINGS"); uint32 driverConfig = ReadDriverConfigurationFlags(); + uint32 serviceConfig = ReadServiceConfigurationFlags(); byte userConfig; string customUserMessage; uint16 bootLoaderVersion = 0; BOOL bPasswordCacheEnabled = (driverConfig & TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD)? TRUE : FALSE; BOOL bPimCacheEnabled = (driverConfig & TC_DRIVER_CONFIG_CACHE_BOOT_PIM)? TRUE : FALSE; + BOOL bBlockSysEncTrimEnabled = (driverConfig & VC_DRIVER_CONFIG_BLOCK_SYS_TRIM)? TRUE : FALSE; + BOOL bClearKeysEnabled = (driverConfig & VC_DRIVER_CONFIG_CLEAR_KEYS_ON_NEW_DEVICE_INSERTION)? TRUE : FALSE; + BOOL bAutoFixBootloader = (serviceConfig & VC_SYSTEM_FAVORITES_SERVICE_CONFIG_DONT_UPDATE_LOADER)? FALSE : TRUE; + BOOL bForceVeraCryptNextBoot = FALSE; + BOOL bForceSetVeraCryptBootEntry = TRUE; + BOOL bForceVeraCryptFirstEntry = TRUE; + if (bSystemIsGPT) + { + bForceVeraCryptNextBoot = (serviceConfig & VC_SYSTEM_FAVORITES_SERVICE_CONFIG_FORCE_SET_BOOTNEXT)? TRUE : FALSE; + bForceSetVeraCryptBootEntry = (serviceConfig & VC_SYSTEM_FAVORITES_SERVICE_CONFIG_DONT_SET_BOOTENTRY)? FALSE : TRUE; + bForceVeraCryptFirstEntry = (serviceConfig & VC_SYSTEM_FAVORITES_SERVICE_CONFIG_DONT_FORCE_FIRST_BOOTENTRY)? FALSE : TRUE; + } + + BOOL bIsHiddenOS = IsHiddenOSRunning (); + + if (bClearKeysEnabled) + { + // the clear keys option works only if the service is running + if (!BootEncObj->IsSystemFavoritesServiceRunning()) + bClearKeysEnabled = false; + } + if (!BootEncObj->ReadBootSectorConfig (nullptr, 0, &userConfig, &customUserMessage, &bootLoaderVersion)) { @@ -11114,6 +12172,10 @@ static BOOL CALLBACK BootLoaderPreferencesDlgProc (HWND hwndDlg, UINT msg, WPARA return 1; } + // we store current configuration in order to be able to detect if user changed it or not after clicking OK + currentUserConfig = userConfig; + currentCustomUserMessage = customUserMessage; + if (bootLoaderVersion != VERSION_NUM) Warning ("BOOT_LOADER_VERSION_INCORRECT_PREFERENCES", hwndDlg); @@ -11147,6 +12209,35 @@ static BOOL CALLBACK BootLoaderPreferencesDlgProc (HWND hwndDlg, UINT msg, WPARA CheckDlgButton (hwndDlg, IDC_BOOT_LOADER_CACHE_PASSWORD, bPasswordCacheEnabled ? BST_CHECKED : BST_UNCHECKED); EnableWindow (GetDlgItem (hwndDlg, IDC_BOOT_LOADER_CACHE_PIM), bPasswordCacheEnabled); CheckDlgButton (hwndDlg, IDC_BOOT_LOADER_CACHE_PIM, (bPasswordCacheEnabled && bPimCacheEnabled)? BST_CHECKED : BST_UNCHECKED); + CheckDlgButton (hwndDlg, IDC_CLEAR_KEYS_ON_NEW_DEVICE_INSERTION, bClearKeysEnabled? BST_CHECKED : BST_UNCHECKED); + + if (bIsHiddenOS) + { + // we always block TRIM command on hidden OS regardless of the configuration + CheckDlgButton (hwndDlg, IDC_BLOCK_SYSENC_TRIM, BST_CHECKED); + EnableWindow (GetDlgItem (hwndDlg, IDC_BLOCK_SYSENC_TRIM), FALSE); + } + else + CheckDlgButton (hwndDlg, IDC_BLOCK_SYSENC_TRIM, bBlockSysEncTrimEnabled ? BST_CHECKED : BST_UNCHECKED); + + CheckDlgButton (hwndDlg, IDC_UPDATE_BOOTLOADER_ON_SHUTDOWN, bAutoFixBootloader? BST_CHECKED : BST_UNCHECKED); + if (bSystemIsGPT) + { + if (!bAutoFixBootloader || bIsHiddenOS) + { + // we disable other options if updating bootloader is not allowed or if hidden OS us running + EnableWindow (GetDlgItem (hwndDlg, IDC_FORCE_NEXT_BOOT_VERACRYPT), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_FORCE_VERACRYPT_BOOT_ENTRY), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_FORCE_VERACRYPT_FIRST_BOOT_ENTRY), FALSE); + } + + if (!bIsHiddenOS) + { + CheckDlgButton (hwndDlg, IDC_FORCE_NEXT_BOOT_VERACRYPT, bForceVeraCryptNextBoot? BST_CHECKED : BST_UNCHECKED); + CheckDlgButton (hwndDlg, IDC_FORCE_VERACRYPT_BOOT_ENTRY, bForceSetVeraCryptBootEntry? BST_CHECKED : BST_UNCHECKED); + CheckDlgButton (hwndDlg, IDC_FORCE_VERACRYPT_FIRST_BOOT_ENTRY, bForceVeraCryptFirstEntry? BST_CHECKED : BST_UNCHECKED); + } + } } catch (Exception &e) { @@ -11173,13 +12264,19 @@ static BOOL CALLBACK BootLoaderPreferencesDlgProc (HWND hwndDlg, UINT msg, WPARA { try { - std::string dcsprop = ReadESPFile (L"\\EFI\\VeraCrypt\\DcsProp", true); + std::string currentDcsprop = ReadESPFile (L"\\EFI\\VeraCrypt\\DcsProp", true); + std::string dcsprop = currentDcsprop; while (TextEditDialogBox(FALSE, hwndDlg, GetString ("BOOT_LOADER_CONFIGURATION_FILE"), dcsprop) == IDOK) { - if (validateDcsPropXml (dcsprop.c_str())) + const char* dcspropContent = dcsprop.c_str(); + if (0 == strcmp(dcspropContent, currentDcsprop.c_str())) + { + break; + } + else if (validateDcsPropXml (dcspropContent)) { - WriteESPFile (L"\\EFI\\VeraCrypt\\DcsProp", (LPBYTE) dcsprop.c_str(), (DWORD) dcsprop.size(), true); + WriteESPFile (L"\\EFI\\VeraCrypt\\DcsProp", (LPBYTE) dcspropContent, (DWORD) strlen (dcspropContent), true); break; } else @@ -11217,17 +12314,7 @@ static BOOL CALLBACK BootLoaderPreferencesDlgProc (HWND hwndDlg, UINT msg, WPARA if (!bSystemIsGPT) GetDlgItemTextA (hwndDlg, IDC_CUSTOM_BOOT_LOADER_MESSAGE, customUserMessage, sizeof (customUserMessage)); - byte userConfig; - try - { - if (!BootEncObj->ReadBootSectorConfig (nullptr, 0, &userConfig)) - return 1; - } - catch (Exception &e) - { - e.Show (hwndDlg); - return 1; - } + byte userConfig = currentUserConfig; if (IsDlgButtonChecked (hwndDlg, IDC_DISABLE_BOOT_LOADER_PIM_PROMPT)) userConfig |= TC_BOOT_USER_CFG_FLAG_DISABLE_PIM; @@ -11236,32 +12323,79 @@ static BOOL CALLBACK BootLoaderPreferencesDlgProc (HWND hwndDlg, UINT msg, WPARA if (bSystemIsGPT) { - if (IsDlgButtonChecked (hwndDlg, IDC_DISABLE_BOOT_LOADER_HASH_PROMPT)) - userConfig |= TC_BOOT_USER_CFG_FLAG_STORE_HASH; - else - userConfig &= ~TC_BOOT_USER_CFG_FLAG_STORE_HASH; + if (IsDlgButtonChecked (hwndDlg, IDC_DISABLE_BOOT_LOADER_HASH_PROMPT)) + userConfig |= TC_BOOT_USER_CFG_FLAG_STORE_HASH; + else + userConfig &= ~TC_BOOT_USER_CFG_FLAG_STORE_HASH; } else { if (IsDlgButtonChecked (hwndDlg, IDC_DISABLE_BOOT_LOADER_OUTPUT)) - userConfig |= TC_BOOT_USER_CFG_FLAG_SILENT_MODE; - else - userConfig &= ~TC_BOOT_USER_CFG_FLAG_SILENT_MODE; + userConfig |= TC_BOOT_USER_CFG_FLAG_SILENT_MODE; + else + userConfig &= ~TC_BOOT_USER_CFG_FLAG_SILENT_MODE; - if (!IsDlgButtonChecked (hwndDlg, IDC_ALLOW_ESC_PBA_BYPASS)) - userConfig |= TC_BOOT_USER_CFG_FLAG_DISABLE_ESC; - else - userConfig &= ~TC_BOOT_USER_CFG_FLAG_DISABLE_ESC; + if (!IsDlgButtonChecked (hwndDlg, IDC_ALLOW_ESC_PBA_BYPASS)) + userConfig |= TC_BOOT_USER_CFG_FLAG_DISABLE_ESC; + else + userConfig &= ~TC_BOOT_USER_CFG_FLAG_DISABLE_ESC; } try { BOOL bPasswordCacheEnabled = IsDlgButtonChecked (hwndDlg, IDC_BOOT_LOADER_CACHE_PASSWORD); BOOL bPimCacheEnabled = IsDlgButtonChecked (hwndDlg, IDC_BOOT_LOADER_CACHE_PIM); - BootEncObj->WriteBootSectorUserConfig (userConfig, customUserMessage, prop.volumePim, prop.pkcs5); + BOOL bBlockSysEncTrimEnabled = IsDlgButtonChecked (hwndDlg, IDC_BLOCK_SYSENC_TRIM); + BOOL bClearKeysEnabled = IsDlgButtonChecked (hwndDlg, IDC_CLEAR_KEYS_ON_NEW_DEVICE_INSERTION); + + BOOL bAutoFixBootloader = IsDlgButtonChecked (hwndDlg, IDC_UPDATE_BOOTLOADER_ON_SHUTDOWN); + BOOL bForceVeraCryptNextBoot = FALSE; + BOOL bForceSetVeraCryptBootEntry = TRUE; + BOOL bForceVeraCryptFirstEntry = TRUE; + if (bSystemIsGPT) + { + bForceVeraCryptNextBoot = IsDlgButtonChecked (hwndDlg, IDC_FORCE_NEXT_BOOT_VERACRYPT); + bForceSetVeraCryptBootEntry = IsDlgButtonChecked (hwndDlg, IDC_FORCE_VERACRYPT_BOOT_ENTRY); + bForceVeraCryptFirstEntry = IsDlgButtonChecked (hwndDlg, IDC_FORCE_VERACRYPT_FIRST_BOOT_ENTRY); + } + + if (bClearKeysEnabled && !BootEncObj->IsSystemFavoritesServiceRunning()) + { + // the system favorite service service should be running + // if it is not the case, report a failure and quit + std::string techInfo = SRC_POS; + techInfo += "\nIsSystemFavoritesServiceRunning = False."; + ReportUnexpectedState (techInfo.c_str()); + return 1; + } + + // only write boot configuration if something changed + if ((userConfig != currentUserConfig) || (!bSystemIsGPT && (customUserMessage != currentCustomUserMessage))) + BootEncObj->WriteBootSectorUserConfig (userConfig, customUserMessage, prop.volumePim, prop.pkcs5); + SetDriverConfigurationFlag (TC_DRIVER_CONFIG_CACHE_BOOT_PASSWORD, bPasswordCacheEnabled); SetDriverConfigurationFlag (TC_DRIVER_CONFIG_CACHE_BOOT_PIM, (bPasswordCacheEnabled && bPimCacheEnabled)? TRUE : FALSE); SetDriverConfigurationFlag (TC_DRIVER_CONFIG_DISABLE_EVIL_MAID_ATTACK_DETECTION, IsDlgButtonChecked (hwndDlg, IDC_DISABLE_EVIL_MAID_ATTACK_DETECTION)); + if (bClearKeysEnabled) + NotifyService (VC_DRIVER_CONFIG_CLEAR_KEYS_ON_NEW_DEVICE_INSERTION); + SetDriverConfigurationFlag (VC_DRIVER_CONFIG_CLEAR_KEYS_ON_NEW_DEVICE_INSERTION, bClearKeysEnabled); + SetServiceConfigurationFlag (VC_SYSTEM_FAVORITES_SERVICE_CONFIG_DONT_UPDATE_LOADER, bAutoFixBootloader? FALSE : TRUE); + if (!IsHiddenOSRunning ()) + { + /* we don't need to update TRIM config for hidden OS since it's always blocked */ + SetDriverConfigurationFlag (VC_DRIVER_CONFIG_BLOCK_SYS_TRIM, bBlockSysEncTrimEnabled); + + if (bSystemIsGPT) + { + if (bAutoFixBootloader) + { + /* we update bootloader settings only if the autofix option is enabled */ + SetServiceConfigurationFlag (VC_SYSTEM_FAVORITES_SERVICE_CONFIG_FORCE_SET_BOOTNEXT, bForceVeraCryptNextBoot); + SetServiceConfigurationFlag (VC_SYSTEM_FAVORITES_SERVICE_CONFIG_DONT_SET_BOOTENTRY, bForceSetVeraCryptBootEntry? FALSE : TRUE); + SetServiceConfigurationFlag (VC_SYSTEM_FAVORITES_SERVICE_CONFIG_DONT_FORCE_FIRST_BOOTENTRY, bForceVeraCryptFirstEntry? FALSE : TRUE); + } + } + } } catch (Exception &e) { @@ -11303,6 +12437,43 @@ static BOOL CALLBACK BootLoaderPreferencesDlgProc (HWND hwndDlg, UINT msg, WPARA } break; + + case IDC_CLEAR_KEYS_ON_NEW_DEVICE_INSERTION: + if (IsDlgButtonChecked (hwndDlg, IDC_CLEAR_KEYS_ON_NEW_DEVICE_INSERTION)) + { + if (!BootEncObj->IsSystemFavoritesServiceRunning()) + { + // the system favorite service service should be running + // if it is not the case, report a failure + std::string techInfo = SRC_POS; + techInfo += "\nIsSystemFavoritesServiceRunning = False."; + ReportUnexpectedState (techInfo.c_str()); + + CheckDlgButton (hwndDlg, IDC_CLEAR_KEYS_ON_NEW_DEVICE_INSERTION, BST_UNCHECKED); + } + else + Warning ("CLEAR_KEYS_ON_DEVICE_INSERTION_WARNING", hwndDlg); + } + + break; + + case IDC_UPDATE_BOOTLOADER_ON_SHUTDOWN: + if (bSystemIsGPT && !IsHiddenOSRunning ()) + { + if (IsDlgButtonChecked (hwndDlg, IDC_UPDATE_BOOTLOADER_ON_SHUTDOWN)) + { + EnableWindow (GetDlgItem (hwndDlg, IDC_FORCE_NEXT_BOOT_VERACRYPT), TRUE); + EnableWindow (GetDlgItem (hwndDlg, IDC_FORCE_VERACRYPT_BOOT_ENTRY), TRUE); + EnableWindow (GetDlgItem (hwndDlg, IDC_FORCE_VERACRYPT_FIRST_BOOT_ENTRY), TRUE); + } + else + { + EnableWindow (GetDlgItem (hwndDlg, IDC_FORCE_NEXT_BOOT_VERACRYPT), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_FORCE_VERACRYPT_BOOT_ENTRY), FALSE); + EnableWindow (GetDlgItem (hwndDlg, IDC_FORCE_VERACRYPT_FIRST_BOOT_ENTRY), FALSE); + } + } + break; } return 0; } @@ -11311,7 +12482,7 @@ static BOOL CALLBACK BootLoaderPreferencesDlgProc (HWND hwndDlg, UINT msg, WPARA } -void MountSelectedVolume (HWND hwndDlg, BOOL mountWithOptions) +void MountSelectedVolume (HWND hwndDlg, BOOL mountWithOptions, BOOL skipCachedPasswords) { if (!VolumeSelected(hwndDlg)) { @@ -11320,6 +12491,7 @@ void MountSelectedVolume (HWND hwndDlg, BOOL mountWithOptions) else if (LOWORD (GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST))) == TC_MLIST_ITEM_FREE) { mountOptions = defaultMountOptions; + mountOptions.SkipCachedPasswords = skipCachedPasswords; bPrebootPasswordDlgMode = FALSE; if (mountWithOptions || GetAsyncKeyState (VK_CONTROL) < 0) @@ -11332,7 +12504,7 @@ void MountSelectedVolume (HWND hwndDlg, BOOL mountWithOptions) else mountOptions.ProtectedHidVolPkcs5Prf = CmdVolumePkcs5; mountOptions.ProtectedHidVolPim = CmdVolumePim; - if (IDCANCEL == DialogBoxParamW (hInst, + if (IDCANCEL == SecureDesktopDialogBoxParam (hInst, MAKEINTRESOURCEW (IDD_MOUNT_OPTIONS), hwndDlg, (DLGPROC) MountOptionsDlgProc, (LPARAM) &mountOptions)) return; |