VeraCrypt
aboutsummaryrefslogtreecommitdiff
path: root/src/ExpandVolume/WinMain.cpp
blob: 7b3d77e5c66d55e888bc425cb456772c228851d5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
/*
 Legal Notice: Some portions of the source code contained in this file were
 derived from the source code of TrueCrypt 7.1a, which is 
 Copyright (c) 2003-2012 TrueCrypt Developers Association and which is 
 governed by the TrueCrypt License 3.0, also from the source code of
 Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux
 and which is governed by the 'License Agreement for Encryption for the Masses' 
 and also from the source code of extcv, which is Copyright (c) 2009-2010 Kih-Oskh
 or Copyright (c) 2012-2013 Josef Schneider <josef@netpage.dk>

 Modifications and additions to the original source code (contained in this file) 
 and all other portions of this file are Copyright (c) 2013-2015 IDRIX
 and are governed by the Apache License 2.0 the full text of which is
 contained in the file License.txt included in VeraCrypt binary and source
 code distribution packages. */

#include "Tcdefs.h"

#include <time.h>
#include <math.h>
#include <dbt.h>
#include <fcntl.h>
#include <io.h>
#include <sys/stat.h>
#include <windowsx.h>

#include "Apidrvr.h"
#include "BootEncryption.h"
#include "Cmdline.h"
#include "Crypto.h"
#include "Dlgcode.h"
#include "Combo.h"
#include "Keyfiles.h"
#include "Language.h"
#include "../Mount/MainCom.h"
#include "../Mount/Mount.h"
#include "Pkcs5.h"
#include "Random.h"
#include "Registry.h"
#include "Resource.h"
#include "Password.h"
#include "Xml.h"
#include "../Boot/Windows/BootCommon.h"
#include "../Common/Dictionary.h"
#include "../Common/Common.h"
#include "../Common/Resource.h"
#include "../Common/SecurityToken.h"
#include "../Platform/Finally.h"
#include "../Platform/ForEach.h"
#include <Strsafe.h>

#include "ExpandVolume.h"

using namespace VeraCrypt;

const wchar_t szExpandVolumeInfo[] =
L":: VeraCrypt Expander ::\n\nExpand a VeraCrypt volume on the fly without reformatting\n\n\n\
All kind of volumes (container files, disks and partitions) formatted with \
NTFS are supported. The only condition is that there must be enough free \
space on the host drive or host device of the VeraCrypt volume.\n\n\
Do not use this software to expand an outer volume containing a hidden \
volume, because this destroys the hidden volume!\n\
";

enum timer_ids
{
	TIMER_ID_MAIN = 0xff,
	TIMER_ID_KEYB_LAYOUT_GUARD
};

enum hidden_os_read_only_notif_mode
{
	TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_NONE = 0,
	TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_COMPACT,
	TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_DISABLED
};

#define TIMER_INTERVAL_MAIN					500
#define TIMER_INTERVAL_KEYB_LAYOUT_GUARD	10

namespace VeraCryptExpander
{

BOOL bExplore = FALSE;				/* Display explorer window after mount */
BOOL bBeep = FALSE;					/* Donot beep after mount */
wchar_t szFileName[TC_MAX_PATH+1];		/* Volume to mount */
wchar_t szDriveLetter[3];				/* Drive Letter to mount */
wchar_t commandLineDrive = 0;
BOOL bCacheInDriver = FALSE;		/* Cache any passwords we see */
BOOL bCacheInDriverDefault = FALSE;
BOOL bHistoryCmdLine = FALSE;		/* History control is always disabled */
BOOL bCloseDismountedWindows=TRUE;	/* Close all open explorer windows of dismounted volume */
BOOL bWipeCacheOnExit = FALSE;		/* Wipe password from chace on exit */
BOOL bWipeCacheOnAutoDismount = TRUE;
BOOL bEnableBkgTask = FALSE;
BOOL bCloseBkgTaskWhenNoVolumes = FALSE;
BOOL bDismountOnLogOff = TRUE;
BOOL bDismountOnScreenSaver = TRUE;
BOOL bDismountOnPowerSaving = FALSE;
BOOL bForceAutoDismount = TRUE;
BOOL bForceMount = FALSE;			/* Mount volume even if host file/device already in use */
BOOL bForceUnmount = FALSE;			/* Unmount volume even if it cannot be locked */
BOOL bWipe = FALSE;					/* Wipe driver passwords */
BOOL bAuto = FALSE;					/* Do everything without user input */
BOOL bAutoMountDevices = FALSE;		/* Auto-mount devices */
BOOL bAutoMountFavorites = FALSE;
BOOL bPlaySoundOnHotkeyMountDismount = TRUE;
BOOL bDisplayMsgBoxOnHotkeyDismount = FALSE;
BOOL bHibernationPreventionNotified = FALSE;	/* TRUE if the user has been notified that hibernation was prevented (system encryption) during the session. */
BOOL bHiddenSysLeakProtNotifiedDuringSession = FALSE;	/* TRUE if the user has been notified during the session that unencrypted filesystems and non-hidden VeraCrypt volumes are mounted as read-only under hidden OS. */
BOOL CloseSecurityTokenSessionsAfterMount = FALSE;

BOOL MultipleMountOperationInProgress = FALSE;

BOOL Quit = FALSE;					/* Exit after processing command line */
BOOL ComServerMode = FALSE;
BOOL UsePreferences = TRUE;

int HiddenSysLeakProtectionNotificationStatus = TC_HIDDEN_OS_READ_ONLY_NOTIF_MODE_NONE;
int MaxVolumeIdleTime = -120;
int nCurrentShowType = 0;			/* current display mode, mount, unmount etc */
int nSelectedDriveIndex = -1;		/* Item number of selected drive */

int cmdUnmountDrive = -2;			/* Volume drive letter to unmount (-1 = all) */
Password VolumePassword;			/* Password used for mounting volumes */
Password CmdVolumePassword;			/* Password passed from command line */
BOOL CmdVolumePasswordValid = FALSE;
MountOptions mountOptions;
MountOptions defaultMountOptions;
KeyFile *FirstCmdKeyFile;

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;
VOLUME_NOTIFICATIONS_LIST	VolumeNotificationsList;

static int bPrebootPasswordDlgMode = FALSE;

static void localcleanup (void)
{
	// Wipe command line
	char *c = GetCommandLineA ();
	wchar_t *wc = GetCommandLineW ();
	burn(c, strlen (c));
	burn(wc, wcslen (wc) * sizeof (wchar_t));

	/* Delete buffered bitmaps (if any) */
	if (hbmLogoBitmapRescaled != NULL)
	{
		DeleteObject ((HGDIOBJ) hbmLogoBitmapRescaled);
		hbmLogoBitmapRescaled = NULL;
	}

	/* These items should have already been cleared by the functions that used them, but we're going to
	clear them for extra security. */
	burn (&VolumePassword, sizeof (VolumePassword));
	burn (&CmdVolumePassword, sizeof (CmdVolumePassword));
	burn (&mountOptions, sizeof (mountOptions));
	burn (&defaultMountOptions, sizeof (defaultMountOptions));
	burn (&szFileName, sizeof(szFileName));

	/* Cleanup common code resources */
	cleanup ();

	RandStop (TRUE);
}


void EndMainDlg (HWND hwndDlg)
{
	if (!bHistory)
	{
		SetWindowText (GetDlgItem (hwndDlg, IDC_VOLUME), L"");
	}

	EndDialog (hwndDlg, 0);
}

BOOL CALLBACK MountOptionsDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	// dummy (referenced by PasswordDlgProc() )
	return FALSE;
}
BOOL TCBootLoaderOnInactiveSysEncDrive (void)
{
	// dummy (referenced by Dlgcode.c)
	return FALSE;
}

BOOL CheckSysEncMountWithoutPBA (const char *devicePath, BOOL quiet)
{
	// dummy (referenced by Dlgcode.c)
	return FALSE;
}

static void InitMainDialog (HWND hwndDlg)
{
	/* Call the common dialog init code */
	InitDialog (hwndDlg);
	LocalizeDialog (hwndDlg, NULL);

	SendMessage (GetDlgItem (hwndDlg, IDC_VOLUME), CB_LIMITTEXT, TC_MAX_PATH, 0);
	SetWindowTextW (hwndDlg, lpszTitle);

	SendMessage (GetDlgItem (hwndDlg, IDC_INFOEXPAND), WM_SETFONT, (WPARAM) hBoldFont, (LPARAM) TRUE);
	SetWindowText (GetDlgItem (hwndDlg, IDC_INFOEXPAND), szExpandVolumeInfo);

	// 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);
	}

	EnableDisableButtons (hwndDlg);
}

void EnableDisableButtons (HWND hwndDlg)
{
	HWND hOKButton = GetDlgItem (hwndDlg, IDOK);
	WORD x;

	x = LOWORD (GetSelectedLong (GetDlgItem (hwndDlg, IDC_DRIVELIST)));

	EnableWindow (hOKButton, TRUE);

}

BOOL VolumeSelected (HWND hwndDlg)
{
	return (GetWindowTextLength (GetDlgItem (hwndDlg, IDC_VOLUME)) > 0);
}


void LoadSettings (HWND hwndDlg)
{
	WipeAlgorithmId savedWipeAlgorithm = TC_WIPE_NONE;

	LoadSysEncSettings (hwndDlg);

	if (LoadNonSysInPlaceEncSettings (&savedWipeAlgorithm) != 0)
		bInPlaceEncNonSysPending = TRUE;

	// If the config file has already been loaded during this session
	if (ConfigBuffer != NULL)
	{
		free (ConfigBuffer);
		ConfigBuffer = NULL;
	}

	// Options
	bExplore =						ConfigReadInt ("OpenExplorerWindowAfterMount", FALSE);
	bCloseDismountedWindows =		ConfigReadInt ("CloseExplorerWindowsOnDismount", TRUE);

	bHistory =						ConfigReadInt ("SaveVolumeHistory", FALSE);

	bCacheInDriverDefault = bCacheInDriver = ConfigReadInt ("CachePasswords", FALSE);
	bWipeCacheOnExit =				ConfigReadInt ("WipePasswordCacheOnExit", FALSE);
	bWipeCacheOnAutoDismount =		ConfigReadInt ("WipeCacheOnAutoDismount", TRUE);

	bStartOnLogon =					ConfigReadInt ("StartOnLogon", FALSE);
	bMountDevicesOnLogon =			ConfigReadInt ("MountDevicesOnLogon", FALSE);
	bMountFavoritesOnLogon =		ConfigReadInt ("MountFavoritesOnLogon", FALSE);

	bEnableBkgTask =				ConfigReadInt ("EnableBackgroundTask", TRUE);
	bCloseBkgTaskWhenNoVolumes =	ConfigReadInt ("CloseBackgroundTaskOnNoVolumes", FALSE);

	bDismountOnLogOff =				ConfigReadInt ("DismountOnLogOff", TRUE);
	bDismountOnPowerSaving =		ConfigReadInt ("DismountOnPowerSaving", FALSE);
	bDismountOnScreenSaver =		ConfigReadInt ("DismountOnScreenSaver", FALSE);
	bForceAutoDismount =			ConfigReadInt ("ForceAutoDismount", TRUE);
	MaxVolumeIdleTime =				ConfigReadInt ("MaxVolumeIdleTime", -60);

	HiddenSectorDetectionStatus =	ConfigReadInt ("HiddenSectorDetectionStatus", 0);

	defaultKeyFilesParam.EnableKeyFiles = ConfigReadInt ("UseKeyfiles", FALSE);

	bPreserveTimestamp = defaultMountOptions.PreserveTimestamp = ConfigReadInt ("PreserveTimestamps", TRUE);
	defaultMountOptions.Removable =	ConfigReadInt ("MountVolumesRemovable", FALSE);
	defaultMountOptions.ReadOnly =	ConfigReadInt ("MountVolumesReadOnly", FALSE);
	defaultMountOptions.ProtectHiddenVolume = FALSE;
	defaultMountOptions.PartitionInInactiveSysEncScope = FALSE;
	defaultMountOptions.RecoveryMode = FALSE;
	defaultMountOptions.UseBackupHeader =  FALSE;

	mountOptions = defaultMountOptions;

	CloseSecurityTokenSessionsAfterMount = ConfigReadInt ("CloseSecurityTokenSessionsAfterMount", 0);

	{
		char szTmp[TC_MAX_PATH] = {0};
		WideCharToMultiByte (CP_UTF8, 0, SecurityTokenLibraryPath, -1, szTmp, sizeof (szTmp), NULL, NULL);
		ConfigReadString ("SecurityTokenLibrary", "", szTmp, sizeof (szTmp) - 1);
		MultiByteToWideChar (CP_UTF8, 0, szTmp, -1, SecurityTokenLibraryPath, ARRAYSIZE (SecurityTokenLibraryPath));

		if (SecurityTokenLibraryPath[0])
			InitSecurityTokenLibrary(hwndDlg);
	}

	/* we don't load the history */
}


BOOL SelectItem (HWND hTree, wchar_t nLetter)
{
	int i;
	LVITEM item;

	for (i = 0; i < ListView_GetItemCount(hTree); i++)
	{
		memset(&item, 0, sizeof(LVITEM));
		item.mask = LVIF_PARAM;
		item.iItem = i;

		if (ListView_GetItem (hTree, &item) == FALSE)
			return FALSE;
		else
		{
			if (HIWORD (item.lParam) == nLetter)
			{
				memset(&item, 0, sizeof(LVITEM));
				item.state = LVIS_FOCUSED|LVIS_SELECTED;
				item.stateMask = LVIS_FOCUSED|LVIS_SELECTED;
				item.mask = LVIF_STATE;
				item.iItem = i;
				SendMessage(hTree, LVM_SETITEMSTATE, i, (LPARAM) &item);
				return TRUE;
			}
		}
	}

	return TRUE;
}



LPARAM
GetSelectedLong (HWND hTree)
{
	int hItem = ListView_GetSelectionMark (hTree);
	LVITEM item;

	if (nSelectedDriveIndex >= 0)
		hItem = nSelectedDriveIndex;

	memset(&item, 0, sizeof(LVITEM));
	item.mask = LVIF_PARAM;
	item.iItem = hItem;

	if (ListView_GetItem (hTree, &item) == FALSE)
		return MAKELONG (0xffff, 0xffff);
	else
		return item.lParam;
}

LPARAM
GetItemLong (HWND hTree, int itemNo)
{
	LVITEM item;

	memset(&item, 0, sizeof(LVITEM));
	item.mask = LVIF_PARAM;
	item.iItem = itemNo;

	if (ListView_GetItem (hTree, &item) == FALSE)
		return MAKELONG (0xffff, 0xffff);
	else
		return item.lParam;
}

static wchar_t PasswordDlgVolume[MAX_PATH + 1] = {0};
static BOOL PasswordDialogDisableMountOptions;
static char *PasswordDialogTitleStringId;

/* Except in response to the WM_INITDIALOG message, the dialog box procedure
   should return nonzero if it processes the message, and zero if it does
   not. - see DialogProc */
BOOL CALLBACK ExtcvPasswordDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	WORD lw = LOWORD (wParam);
	static Password *szXPwd;
	static int *pkcs5;
	static int *pim;
	static BOOL* truecryptMode;

	switch (msg)
	{
	case WM_INITDIALOG:
		{
			int i, nIndex;
			szXPwd = ((PasswordDlgParam *) lParam) -> password;
			pkcs5 = ((PasswordDlgParam *) lParam) -> pkcs5;
			pim = ((PasswordDlgParam *) lParam) -> pim;
			truecryptMode = ((PasswordDlgParam *) lParam) -> truecryptMode;
			LocalizeDialog (hwndDlg, "IDD_PASSWORD_DLG");
			DragAcceptFiles (hwndDlg, TRUE);

			if (PasswordDialogTitleStringId)
			{
				SetWindowTextW (hwndDlg, GetString (PasswordDialogTitleStringId));
			}
			else if (wcslen (PasswordDlgVolume) > 0)
			{
				wchar_t s[1024];
				const int maxVisibleLen = 40;

				if (wcslen (PasswordDlgVolume) > maxVisibleLen)
				{
					wstring volStr = PasswordDlgVolume;
					StringCbPrintfW (s, sizeof(s), GetString ("ENTER_PASSWORD_FOR"), (L"..." + volStr.substr (volStr.size() - maxVisibleLen - 1)).c_str());
				}
				else
					StringCbPrintfW (s, sizeof(s), GetString ("ENTER_PASSWORD_FOR"), PasswordDlgVolume);

				SetWindowTextW (hwndDlg, s);
			}

			/* Populate the PRF algorithms list */
			HWND hComboBox = GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID);
			SendMessage (hComboBox, CB_RESETCONTENT, 0, 0);

			nIndex = SendMessageW (hComboBox, CB_ADDSTRING, 0, (LPARAM) GetString ("AUTODETECTION"));
			SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) 0);

			for (i = FIRST_PRF_ID; i <= LAST_PRF_ID; i++)
			{
				nIndex = SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) get_pkcs5_prf_name(i));
				SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) i);
			}

			/* make autodetection the default */
			SendMessage (hComboBox, CB_SETCURSEL, 0, 0);

			SendMessage (GetDlgItem (hwndDlg, IDC_PASSWORD), EM_LIMITTEXT, MAX_PASSWORD, 0);
			SendMessage (GetDlgItem (hwndDlg, IDC_CACHE), BM_SETCHECK, bCacheInDriver ? BST_CHECKED:BST_UNCHECKED, 0);
			SendMessage (GetDlgItem (hwndDlg, IDC_PIM), EM_LIMITTEXT, MAX_PIM, 0);

			SetPim (hwndDlg, IDC_PIM, *pim);

			/* make PIM field visible if a PIM value has been explicitely specified */
			if (*pim > 0)
			{
				ShowWindow (GetDlgItem (hwndDlg, IDC_PIM_ENABLE), SW_HIDE);
				ShowWindow (GetDlgItem( hwndDlg, IDT_PIM), SW_SHOW);
				ShowWindow (GetDlgItem( hwndDlg, IDC_PIM), SW_SHOW);
				ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_HELP), SW_SHOW);
			}

			SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable);

			mountOptions.PartitionInInactiveSysEncScope = bPrebootPasswordDlgMode;

			if (bPrebootPasswordDlgMode)
			{
				SendMessage (hwndDlg, TC_APPMSG_PREBOOT_PASSWORD_MODE, 0, 0);
			}

			if (PasswordDialogDisableMountOptions)
			{
				EnableWindow (GetDlgItem (hwndDlg, IDC_CACHE), FALSE);
				EnableWindow (GetDlgItem (hwndDlg, IDC_MOUNT_OPTIONS), FALSE);
			}

			/* No support for mounting TrueCrypt volumes */				
			SetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE, FALSE);
			EnableWindow (GetDlgItem (hwndDlg, IDC_TRUECRYPT_MODE), FALSE);

			if (!SetForegroundWindow (hwndDlg) && (FavoriteMountOnArrivalInProgress))
			{
				SetWindowPos (hwndDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);

				FLASHWINFO flash;
				flash.cbSize = sizeof (flash);
				flash.dwFlags = FLASHW_ALL | FLASHW_TIMERNOFG;
				flash.dwTimeout = 0;
				flash.hwnd = hwndDlg;
				flash.uCount = 0;

				FlashWindowEx (&flash);

				SetWindowPos (hwndDlg, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
			}
		}
		return 0;

	case TC_APPMSG_PREBOOT_PASSWORD_MODE:
		{
			/* No support for mounting TrueCrypt system partition */				
			SetCheckBox (hwndDlg, IDC_TRUECRYPT_MODE, FALSE);
			EnableWindow (GetDlgItem (hwndDlg, IDC_TRUECRYPT_MODE), FALSE);

			/* Repopulate the PRF algorithms list with algorithms that support system encryption */
			HWND hComboBox = GetDlgItem (hwndDlg, IDC_PKCS5_PRF_ID);
			SendMessage (hComboBox, CB_RESETCONTENT, 0, 0);

			int i, nIndex = SendMessageW (hComboBox, CB_ADDSTRING, 0, (LPARAM) GetString ("AUTODETECTION"));
			SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) 0);

			for (i = FIRST_PRF_ID; i <= LAST_PRF_ID; i++)
			{
				if (HashForSystemEncryption(i))
				{
					nIndex = SendMessage (hComboBox, CB_ADDSTRING, 0, (LPARAM) get_pkcs5_prf_name(i));
					SendMessage (hComboBox, CB_SETITEMDATA, nIndex, (LPARAM) i);
				}
			}

			/* make autodetection the default */
			SendMessage (hComboBox, CB_SETCURSEL, 0, 0);

			ToBootPwdField (hwndDlg, IDC_PASSWORD);

			// Attempt to wipe the password stored in the input field buffer
			wchar_t tmp[MAX_PASSWORD+1];
			wmemset (tmp, L'X', MAX_PASSWORD);
			tmp [MAX_PASSWORD] = 0;
			SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp);
			SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), L"");

			StringCbPrintfW (OrigKeyboardLayout, sizeof(OrigKeyboardLayout),L"%08X", (DWORD) GetKeyboardLayout (NULL) & 0xFFFF);

			DWORD keybLayout = (DWORD) LoadKeyboardLayout (L"00000409", KLF_ACTIVATE);

			if (keybLayout != 0x00000409 && keybLayout != 0x04090409)
			{
				Error ("CANT_CHANGE_KEYB_LAYOUT_FOR_SYS_ENCRYPTION", hwndDlg);
				EndDialog (hwndDlg, IDCANCEL);
				return 1;
			}

			if (SetTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD, TIMER_INTERVAL_KEYB_LAYOUT_GUARD, NULL) == 0)
			{
				Error ("CANNOT_SET_TIMER", hwndDlg);
				EndDialog (hwndDlg, IDCANCEL);
				return 1;
			}

			if (GetCheckBox (hwndDlg, IDC_SHOW_PASSWORD))
			{
				// simulate hiding password
				SetCheckBox (hwndDlg, IDC_SHOW_PASSWORD, FALSE);

				HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PASSWORD, IDC_PASSWORD, IDC_PIM);
			}

			SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, FALSE);
			EnableWindow (GetDlgItem (hwndDlg, IDC_KEYFILES_ENABLE), FALSE);
			EnableWindow (GetDlgItem (hwndDlg, IDC_KEY_FILES), FALSE);

			SetPim (hwndDlg, IDC_PIM, *pim);

			bPrebootPasswordDlgMode = TRUE;
		}
		return 1;

	case WM_TIMER:
		switch (wParam)
		{
		case TIMER_ID_KEYB_LAYOUT_GUARD:
			if (bPrebootPasswordDlgMode)
			{
				DWORD keybLayout = (DWORD) GetKeyboardLayout (NULL);

				if (keybLayout != 0x00000409 && keybLayout != 0x04090409)
				{
					// Keyboard layout is not standard US

					// Attempt to wipe the password stored in the input field buffer
					wchar_t tmp[MAX_PASSWORD+1];
					wmemset (tmp, L'X', MAX_PASSWORD);
					tmp [MAX_PASSWORD] = 0;
					SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp);
					SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), L"");

					keybLayout = (DWORD) LoadKeyboardLayout (L"00000409", KLF_ACTIVATE);

					if (keybLayout != 0x00000409 && keybLayout != 0x04090409)
					{
						KillTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD);
						Error ("CANT_CHANGE_KEYB_LAYOUT_FOR_SYS_ENCRYPTION", hwndDlg);
						EndDialog (hwndDlg, IDCANCEL);
						return 1;
					}

					wchar_t szTmp [4096];
					StringCbCopyW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_CHANGE_PREVENTED"));
					StringCbCatW (szTmp, sizeof(szTmp), L"\n\n");
					StringCbCatW (szTmp, sizeof(szTmp), GetString ("KEYB_LAYOUT_SYS_ENC_EXPLANATION"));
					MessageBoxW (MainDlg, szTmp, lpszTitle, MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST);
				}
			}
			return 1;
		}
		return 0;

	case WM_COMMAND:

		if (lw == IDC_MOUNT_OPTIONS)
		{
			DialogBoxParamW (hInst, 
				MAKEINTRESOURCEW (IDD_MOUNT_OPTIONS), hwndDlg,
				(DLGPROC) MountOptionsDlgProc, (LPARAM) &mountOptions);

			if (!bPrebootPasswordDlgMode && mountOptions.PartitionInInactiveSysEncScope)
				SendMessage (hwndDlg, TC_APPMSG_PREBOOT_PASSWORD_MODE, 0, 0);

			return 1;
		}

		if (lw == IDC_PIM_ENABLE)
		{
			ShowWindow (GetDlgItem (hwndDlg, IDC_PIM_ENABLE), SW_HIDE);
			ShowWindow (GetDlgItem( hwndDlg, IDT_PIM), SW_SHOW);
			ShowWindow (GetDlgItem( hwndDlg, IDC_PIM), SW_SHOW);
			ShowWindow (GetDlgItem( hwndDlg, IDC_PIM_HELP), SW_SHOW);

			SetFocus (GetDlgItem (hwndDlg, IDC_PIM));
			return 1;
		}

		if (lw == IDC_SHOW_PASSWORD)
		{
			HandleShowPasswordFieldAction (hwndDlg, IDC_SHOW_PASSWORD, IDC_PASSWORD, IDC_PIM);
			return 1;
		}

		if (lw == IDC_KEY_FILES)
		{
			KeyFilesDlgParam param;
			param.EnableKeyFiles = KeyFilesEnable;
			param.FirstKeyFile = FirstKeyFile;

			if (IDOK == DialogBoxParamW (hInst,
				MAKEINTRESOURCEW (IDD_KEYFILES), hwndDlg,
				(DLGPROC) KeyFilesDlgProc, (LPARAM) &param))
			{
				KeyFilesEnable = param.EnableKeyFiles;
				FirstKeyFile = param.FirstKeyFile;

				SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable);
			}

			return 1;
		}

		if (lw == IDC_KEYFILES_ENABLE)
		{
			KeyFilesEnable = GetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE);

			return 1;
		}

		if (lw == IDCANCEL || lw == IDOK)
		{
			wchar_t tmp[MAX_PASSWORD+1];

			if (lw == IDOK)
			{
				if (mountOptions.ProtectHiddenVolume && hidVolProtKeyFilesParam.EnableKeyFiles)
					KeyFilesApply (hwndDlg, &mountOptions.ProtectedHidVolPassword, hidVolProtKeyFilesParam.FirstKeyFile, PasswordDlgVolume);

				if (GetPassword (hwndDlg, IDC_PASSWORD, (LPSTR) szXPwd->Text, MAX_PASSWORD + 1, TRUE))
					szXPwd->Length = 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);

				/* SHA-256 is not supported by TrueCrypt */
				if (	(*truecryptMode) 
					&& ((*pkcs5 == SHA256) || (mountOptions.ProtectHiddenVolume && mountOptions.ProtectedHidVolPkcs5Prf == SHA256))
					)
				{
					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
			wmemset (tmp, L'X', MAX_PASSWORD);
			tmp[MAX_PASSWORD] = 0;
			SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD), tmp);	
			SetWindowText (GetDlgItem (hwndDlg, IDC_PASSWORD_PROT_HIDVOL), tmp);			

			if (hidVolProtKeyFilesParam.FirstKeyFile != NULL)
			{
				KeyFileRemoveAll (&hidVolProtKeyFilesParam.FirstKeyFile);
				hidVolProtKeyFilesParam.EnableKeyFiles = FALSE;
			}

			if (bPrebootPasswordDlgMode)
			{
				KillTimer (hwndDlg, TIMER_ID_KEYB_LAYOUT_GUARD);

				// Restore the original keyboard layout
				if (LoadKeyboardLayout (OrigKeyboardLayout, KLF_ACTIVATE | KLF_SUBSTITUTE_OK) == NULL) 
					Warning ("CANNOT_RESTORE_KEYBOARD_LAYOUT", hwndDlg);
			}

			EndDialog (hwndDlg, lw);
			return 1;
		}
		return 0;

	case WM_CONTEXTMENU:
		{
			RECT buttonRect;
			GetWindowRect (GetDlgItem (hwndDlg, IDC_KEY_FILES), &buttonRect);

			if (LOWORD (lParam) >= buttonRect.left && LOWORD (lParam) <= buttonRect.right
				&& HIWORD (lParam) >= buttonRect.top && HIWORD (lParam) <= buttonRect.bottom)
			{
				// The "Keyfiles" button has been right-clicked

				KeyFilesDlgParam param;
				param.EnableKeyFiles = KeyFilesEnable;
				param.FirstKeyFile = FirstKeyFile;

				POINT popupPos;
				popupPos.x = buttonRect.left + 2;
				popupPos.y = buttonRect.top + 2;

				if (KeyfilesPopupMenu (hwndDlg, popupPos, &param))
				{
					KeyFilesEnable = param.EnableKeyFiles;
					FirstKeyFile = param.FirstKeyFile;
					SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable);
				}
			}
		}
		break; 

	case WM_DROPFILES:
		{
			HDROP hdrop = (HDROP) wParam;
			int i = 0, count = DragQueryFile (hdrop, 0xFFFFFFFF, NULL, 0);

			while (count-- > 0)
			{
				KeyFile *kf = (KeyFile *) malloc (sizeof (KeyFile));
				if (kf)
				{
					DragQueryFile (hdrop, i++, kf->FileName, sizeof (kf->FileName));
					FirstKeyFile = KeyFileAdd (FirstKeyFile, kf);
					KeyFilesEnable = TRUE;
				}
			}

			SetCheckBox (hwndDlg, IDC_KEYFILES_ENABLE, KeyFilesEnable);
			DragFinish (hdrop);
		}
		return 1;
	}

	return 0;
}

void SaveSettings (HWND hwndDlg)
{
	// dummy
}

int BackupVolumeHeader (HWND hwndDlg, BOOL bRequireConfirmation, char *lpszVolume)
{
	// dummy
	return 0;
}

int RestoreVolumeHeader (HWND hwndDlg, char *lpszVolume)
{
	// dummy
	return 0;
}

int ExtcvAskVolumePassword (HWND hwndDlg, const wchar_t* fileName, Password *password, int *pkcs5, int *pim, BOOL* truecryptMode, char *titleStringId, BOOL enableMountOptions)
{
	int result;
	PasswordDlgParam dlgParam;

	PasswordDialogTitleStringId = titleStringId;
	PasswordDialogDisableMountOptions = !enableMountOptions;

	dlgParam.password = password;
	dlgParam.pkcs5 = pkcs5;
	dlgParam.pim = pim;
	dlgParam.truecryptMode = truecryptMode;

	StringCbCopyW (PasswordDlgVolume, sizeof(PasswordDlgVolume), fileName);

	result = DialogBoxParamW (hInst, 
		MAKEINTRESOURCEW (IDD_PASSWORD_DLG), hwndDlg,
		(DLGPROC) ExtcvPasswordDlgProc, (LPARAM) &dlgParam);

	if (result != IDOK)
	{
		password->Length = 0;
		*pkcs5 = 0;
		*pim = 0;
		*truecryptMode = FALSE;
		burn (&mountOptions.ProtectedHidVolPassword, sizeof (mountOptions.ProtectedHidVolPassword));
		burn (&mountOptions.ProtectedHidVolPkcs5Prf, sizeof (mountOptions.ProtectedHidVolPkcs5Prf));
	}

	return result == IDOK;
}

// GUI actions

static BOOL SelectContainer (HWND hwndDlg)
{
	if (BrowseFiles (hwndDlg, "OPEN_VOL_TITLE", szFileName, bHistory, FALSE, NULL) == FALSE)
		return FALSE;

	AddComboItem (GetDlgItem (hwndDlg, IDC_VOLUME), szFileName, bHistory);
	VeraCryptExpander::EnableDisableButtons (hwndDlg);
	SetFocus (GetDlgItem (hwndDlg, IDC_DRIVELIST));
	return TRUE;
}

static BOOL SelectPartition (HWND hwndDlg)
{
	RawDevicesDlgParam param;
	param.pszFileName = szFileName;
	int nResult = DialogBoxParamW (hInst, MAKEINTRESOURCEW (IDD_RAWDEVICES_DLG), hwndDlg,
		(DLGPROC) RawDevicesDlgProc, (LPARAM) & param);
	if (nResult == IDOK)
	{
		AddComboItem (GetDlgItem (hwndDlg, IDC_VOLUME), szFileName, bHistory);
		VeraCryptExpander::EnableDisableButtons (hwndDlg);
		SetFocus (GetDlgItem (hwndDlg, IDC_DRIVELIST));
		return TRUE;
	}

	return FALSE;
}


/* 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. */
BOOL CALLBACK MainDialogProc (HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	static UINT taskBarCreatedMsg;
	WORD lw = LOWORD (wParam);

	switch (uMsg)
	{

	case WM_INITDIALOG:
		{
			int exitCode = 0;

			MainDlg = hwndDlg;

			// Set critical default options in case UsePreferences is false
			bPreserveTimestamp = defaultMountOptions.PreserveTimestamp = TRUE;

			if (UsePreferences)
			{
				// General preferences
				VeraCryptExpander::LoadSettings (hwndDlg);

				// Keyfiles
				LoadDefaultKeyFilesParam ();
				RestoreDefaultKeyFilesParam ();
			}

			InitMainDialog (hwndDlg);

			// Quit
			if (Quit)
			{
				exit (exitCode);
			}

			Silent = FALSE;
		}
		return 0;

	case WM_SYSCOMMAND:
		if (lw == IDC_ABOUT)
		{
			DialogBoxW (hInst, MAKEINTRESOURCEW (IDD_ABOUT_DLG), hwndDlg, (DLGPROC) AboutDlgProc);
			return 1;
		}
		return 0;

	case WM_ENDSESSION:
		VeraCryptExpander::EndMainDlg (hwndDlg);
		localcleanup ();
		return 0;

	case WM_COMMAND:

		if (lw == IDCANCEL || lw == IDC_EXIT)
		{
			VeraCryptExpander::EndMainDlg (hwndDlg);
			return 1;
		}

		if ( lw == IDOK )
		{
			if (!VeraCryptExpander::VolumeSelected(hwndDlg))
			{
				Warning ("NO_VOLUME_SELECTED", hwndDlg);
			}
			else
			{
				wchar_t fileName[MAX_PATH];
				GetWindowText (GetDlgItem (hwndDlg, IDC_VOLUME), fileName, ARRAYSIZE (fileName));
				ExpandVolumeWizard(hwndDlg, fileName);
			}
			return 1;
		}

		if (lw == IDM_ABOUT )
		{
			DialogBoxW (hInst, MAKEINTRESOURCEW (IDD_ABOUT_DLG), hwndDlg, (DLGPROC) AboutDlgProc);
			return 1;
		}

		if (lw == IDM_HOMEPAGE )
		{
			ArrowWaitCursor ();
			ShellExecute (NULL, L"open", L"https://veracrypt.codeplex.com", NULL, NULL, SW_SHOWNORMAL);
			Sleep (200);
			NormalCursor ();

			return 1;
		}

		if (lw == IDC_SELECT_FILE)
		{
			SelectContainer (hwndDlg);
			return 1;
		}

		if (lw == IDC_SELECT_DEVICE)
		{
			SelectPartition (hwndDlg);
			return 1;
		}

		return 0;

	case WM_CLOSE:
		VeraCryptExpander::EndMainDlg (hwndDlg);
		return 1;

	default:
		;
	}

	return 0;
}

}


int WINAPI wWinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, wchar_t *lpszCommandLine, int nCmdShow)
{
	int status;
	atexit (VeraCryptExpander::localcleanup);
	SetProcessShutdownParameters (0x100, 0);

	VirtualLock (&VeraCryptExpander::VolumePassword, sizeof (VeraCryptExpander::VolumePassword));
	VirtualLock (&VeraCryptExpander::CmdVolumePassword, sizeof (VeraCryptExpander::CmdVolumePassword));
	VirtualLock (&VeraCryptExpander::mountOptions, sizeof (VeraCryptExpander::mountOptions));
	VirtualLock (&VeraCryptExpander::defaultMountOptions, sizeof (VeraCryptExpander::defaultMountOptions));
	VirtualLock (&VeraCryptExpander::szFileName, sizeof(VeraCryptExpander::szFileName));

	InitCommonControls ();
	InitApp (hInstance, lpszCommandLine);

	/* application title */
	lpszTitle = L"VeraCrypt Expander";

	status = DriverAttach ();
	if (status != 0)
	{
		if (status == ERR_OS_ERROR)
			handleWin32Error (NULL, SRC_POS);
		else
			handleError (NULL, status, SRC_POS);

		AbortProcess ("NODRIVER");
	}

	/* Create the main dialog box */
	DialogBoxParamW (hInstance, MAKEINTRESOURCEW (IDD_MOUNT_DLG), NULL, (DLGPROC) VeraCryptExpander::MainDialogProc,
			(LPARAM) lpszCommandLine);

	/* Terminate */
	return 0;
}