forked from FreeApophis/TrueCrypt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TCFORMAT.C
9004 lines (7255 loc) · 260 KB
/
TCFORMAT.C
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
/*
Legal Notice: Some portions of the source code contained in this file were
derived from the source code of Encryption for the Masses 2.02a, which is
Copyright (c) 1998-2000 Paul Le Roux and which is governed by the 'License
Agreement for Encryption for the Masses'. Modifications and additions to
the original source code (contained in this file) and all other portions
of this file are Copyright (c) 2003-2010 TrueCrypt Developers Association
and are governed by the TrueCrypt License 3.0 the full text of which is
contained in the file License.txt included in TrueCrypt binary and source
code distribution packages. */
#include "Tcdefs.h"
#include <stdlib.h>
#include <limits.h>
#include <time.h>
#include <errno.h>
#include <io.h>
#include <sys/stat.h>
#include <shlobj.h>
#include "Crypto.h"
#include "Apidrvr.h"
#include "Dlgcode.h"
#include "Language.h"
#include "Combo.h"
#include "Registry.h"
#include "Boot/Windows/BootDefs.h"
#include "Common/Common.h"
#include "Common/BootEncryption.h"
#include "Common/Dictionary.h"
#include "Common/Endian.h"
#include "Common/resource.h"
#include "Platform/Finally.h"
#include "Platform/ForEach.h"
#include "Random.h"
#include "Fat.h"
#include "InPlace.h"
#include "Resource.h"
#include "TcFormat.h"
#include "Format.h"
#include "FormatCom.h"
#include "Password.h"
#include "Progress.h"
#include "Tests.h"
#include "Cmdline.h"
#include "Volumes.h"
#include "Wipe.h"
#include "Xml.h"
using namespace TrueCrypt;
enum wizard_pages
{
/* IMPORTANT: IF YOU ADD/REMOVE/MOVE ANY PAGES THAT ARE RELATED TO SYSTEM ENCRYPTION,
REVISE THE 'DECOY_OS_INSTRUCTIONS_PORTION_??' STRINGS! */
INTRO_PAGE,
SYSENC_TYPE_PAGE,
SYSENC_HIDDEN_OS_REQ_CHECK_PAGE,
SYSENC_SPAN_PAGE,
SYSENC_PRE_DRIVE_ANALYSIS_PAGE,
SYSENC_DRIVE_ANALYSIS_PAGE,
SYSENC_MULTI_BOOT_MODE_PAGE,
SYSENC_MULTI_BOOT_SYS_EQ_BOOT_PAGE,
SYSENC_MULTI_BOOT_NBR_SYS_DRIVES_PAGE,
SYSENC_MULTI_BOOT_ADJACENT_SYS_PAGE,
SYSENC_MULTI_BOOT_NONWIN_BOOT_LOADER_PAGE,
SYSENC_MULTI_BOOT_OUTCOME_PAGE,
VOLUME_TYPE_PAGE,
HIDDEN_VOL_WIZARD_MODE_PAGE,
VOLUME_LOCATION_PAGE,
DEVICE_TRANSFORM_MODE_PAGE,
HIDDEN_VOL_HOST_PRE_CIPHER_PAGE,
HIDDEN_VOL_PRE_CIPHER_PAGE,
CIPHER_PAGE,
SIZE_PAGE,
HIDDEN_VOL_HOST_PASSWORD_PAGE,
PASSWORD_PAGE,
FILESYS_PAGE,
SYSENC_COLLECTING_RANDOM_DATA_PAGE,
SYSENC_KEYS_GEN_PAGE,
SYSENC_RESCUE_DISK_CREATION_PAGE,
SYSENC_RESCUE_DISK_BURN_PAGE,
SYSENC_RESCUE_DISK_VERIFIED_PAGE,
SYSENC_WIPE_MODE_PAGE,
SYSENC_PRETEST_INFO_PAGE,
SYSENC_PRETEST_RESULT_PAGE,
SYSENC_ENCRYPTION_PAGE,
NONSYS_INPLACE_ENC_RESUME_PASSWORD_PAGE,
NONSYS_INPLACE_ENC_RESUME_PARTITION_SEL_PAGE,
NONSYS_INPLACE_ENC_RAND_DATA_PAGE,
NONSYS_INPLACE_ENC_WIPE_MODE_PAGE,
NONSYS_INPLACE_ENC_ENCRYPTION_PAGE,
NONSYS_INPLACE_ENC_ENCRYPTION_FINISHED_PAGE,
FORMAT_PAGE,
FORMAT_FINISHED_PAGE,
SYSENC_HIDDEN_OS_INITIAL_INFO_PAGE,
SYSENC_HIDDEN_OS_WIPE_INFO_PAGE,
DEVICE_WIPE_MODE_PAGE,
DEVICE_WIPE_PAGE
};
#define TIMER_INTERVAL_RANDVIEW 30
#define TIMER_INTERVAL_SYSENC_PROGRESS 30
#define TIMER_INTERVAL_NONSYS_INPLACE_ENC_PROGRESS 30
#define TIMER_INTERVAL_SYSENC_DRIVE_ANALYSIS_PROGRESS 100
#define TIMER_INTERVAL_WIPE_PROGRESS 30
#define TIMER_INTERVAL_KEYB_LAYOUT_GUARD 10
enum sys_encryption_cmd_line_switches
{
SYSENC_COMMAND_NONE = 0,
SYSENC_COMMAND_RESUME,
SYSENC_COMMAND_STARTUP_SEQ_RESUME,
SYSENC_COMMAND_ENCRYPT,
SYSENC_COMMAND_DECRYPT,
SYSENC_COMMAND_CREATE_HIDDEN_OS,
SYSENC_COMMAND_CREATE_HIDDEN_OS_ELEV
};
typedef struct
{
int NumberOfSysDrives; // Number of drives that contain an operating system. -1: unknown, 1: one, 2: two or more
int MultipleSystemsOnDrive; // Multiple systems are installed on the drive where the currently running system resides. -1: unknown, 0: no, 1: yes
int BootLoaderLocation; // Boot loader (boot manager) installed in: 1: MBR/1st cylinder, 0: partition/bootsector: -1: unknown
int BootLoaderBrand; // -1: unknown, 0: Microsoft Windows, 1: any non-Windows boot manager/loader
int SystemOnBootDrive; // If the currently running operating system is installed on the boot drive. -1: unknown, 0: no, 1: yes
} SYSENC_MULTIBOOT_CFG;
#define SYSENC_PAUSE_RETRY_INTERVAL 100
#define SYSENC_PAUSE_RETRIES 200
// Expected duration of system drive analysis, in ms
#define SYSENC_DRIVE_ANALYSIS_ETA (4*60000)
BootEncryption *BootEncObj = NULL;
BootEncryptionStatus BootEncStatus;
HWND hCurPage = NULL; /* Handle to current wizard page */
int nCurPageNo = -1; /* The current wizard page */
int nLastPageNo = -1;
volatile int WizardMode = DEFAULT_VOL_CREATION_WIZARD_MODE; /* IMPORTANT: Never change this value directly -- always use ChangeWizardMode() instead. */
volatile BOOL bHiddenOS = FALSE; /* If TRUE, we are performing or (or supposed to perform) actions relating to an operating system installed in a hidden volume (i.e., encrypting a decoy OS partition or creating the outer/hidden volume for the hidden OS). To determine or set the phase of the process, call ChangeHiddenOSCreationPhase() and DetermineHiddenOSCreationPhase()) */
BOOL bDirectSysEncMode = FALSE;
BOOL bDirectSysEncModeCommand = SYSENC_COMMAND_NONE;
BOOL DirectDeviceEncMode = FALSE;
BOOL DirectNonSysInplaceEncResumeMode = FALSE;
BOOL DirectPromptNonSysInplaceEncResumeMode = FALSE;
volatile BOOL bInPlaceEncNonSys = FALSE; /* If TRUE, existing data on a non-system partition/volume are to be encrypted (for system encryption, this flag is ignored) */
volatile BOOL bInPlaceEncNonSysResumed = FALSE; /* If TRUE, the wizard is supposed to resume (or has resumed) process of non-system in-place encryption. */
volatile BOOL bFirstNonSysInPlaceEncResumeDone = FALSE;
__int64 NonSysInplaceEncBytesDone = 0;
__int64 NonSysInplaceEncTotalSize = 0;
BOOL bDeviceTransformModeChoiceMade = FALSE; /* TRUE if the user has at least once manually selected the 'in-place' or 'format' option (on the 'device transform mode' page). */
int nNeedToStoreFilesOver4GB = 0; /* Whether the user wants to be able to store files larger than 4GB on the volume: -1 = Undecided or error, 0 = No, 1 = Yes */
int nVolumeEA = 1; /* Default encryption algorithm */
BOOL bSystemEncryptionInProgress = FALSE; /* TRUE when encrypting/decrypting the system partition/drive (FALSE when paused). */
BOOL bWholeSysDrive = FALSE; /* Whether to encrypt the entire system drive or just the system partition. */
static BOOL bSystemEncryptionStatusChanged = FALSE; /* TRUE if this instance changed the value of SystemEncryptionStatus (it's set to FALSE each time the system encryption settings are saved to the config file). This value is to be treated as protected -- only the wizard can change this value (others may only read it). */
volatile BOOL bSysEncDriveAnalysisInProgress = FALSE;
volatile BOOL bSysEncDriveAnalysisTimeOutOccurred = FALSE;
int SysEncDetectHiddenSectors = -1; /* Whether the user wants us to detect and encrypt the Host Protect Area (if any): -1 = Undecided or error, 0 = No, 1 = Yes */
int SysEncDriveAnalysisStart;
BOOL bDontVerifyRescueDisk = FALSE;
BOOL bFirstSysEncResumeDone = FALSE;
int nMultiBoot = 0; /* The number of operating systems installed on the computer, according to the user. 0: undetermined, 1: one, 2: two or more */
volatile BOOL bHiddenVol = FALSE; /* If true, we are (or will be) creating a hidden volume. */
volatile BOOL bHiddenVolHost = FALSE; /* If true, we are (or will be) creating the host volume (called "outer") for a hidden volume. */
volatile BOOL bHiddenVolDirect = FALSE; /* If true, the wizard omits creating a host volume in the course of the process of hidden volume creation. */
volatile BOOL bHiddenVolFinished = FALSE;
int hiddenVolHostDriveNo = -1; /* Drive letter for the volume intended to host a hidden volume. */
BOOL bRemovableHostDevice = FALSE; /* TRUE when creating a device/partition-hosted volume on a removable device. State undefined when creating file-hosted volumes. */
int realClusterSize; /* Parameter used when determining the maximum possible size of a hidden volume. */
int hash_algo = DEFAULT_HASH_ALGORITHM; /* Which PRF to use in header key derivation (PKCS #5) and in the RNG. */
unsigned __int64 nUIVolumeSize = 0; /* The volume size. Important: This value is not in bytes. It has to be multiplied by nMultiplier. Do not use this value when actually creating the volume (it may chop off sector size, if it is not a multiple of 1024 bytes). */
unsigned __int64 nVolumeSize = 0; /* The volume size, in bytes. */
unsigned __int64 nHiddenVolHostSize = 0; /* Size of the hidden volume host, in bytes */
__int64 nMaximumHiddenVolSize = 0; /* Maximum possible size of the hidden volume, in bytes */
__int64 nbrFreeClusters = 0;
int nMultiplier = BYTES_PER_MB; /* Size selection multiplier. */
char szFileName[TC_MAX_PATH+1]; /* The file selected by the user */
char szDiskFile[TC_MAX_PATH+1]; /* Fully qualified name derived from szFileName */
char szRescueDiskISO[TC_MAX_PATH+1]; /* The filename and path to the Rescue Disk ISO file to be burned (for boot encryption) */
BOOL bDeviceWipeInProgress = FALSE;
volatile BOOL bTryToCorrectReadErrors = FALSE;
volatile BOOL DiscardUnreadableEncryptedSectors = FALSE;
volatile BOOL bVolTransformThreadCancel = FALSE; /* TRUE if the user cancels/pauses volume encryption/format */
volatile BOOL bVolTransformThreadRunning = FALSE; /* Is the volume encryption/format thread running */
volatile BOOL bVolTransformThreadToRun = FALSE; /* TRUE if the Format/Encrypt button has been clicked and we are proceeding towards launching the thread. */
volatile BOOL bConfirmQuit = FALSE; /* If TRUE, the user is asked to confirm exit when he clicks the X icon, Exit, etc. */
volatile BOOL bConfirmQuitSysEncPretest = FALSE;
BOOL bDevice = FALSE; /* Is this a partition volume ? */
BOOL showKeys = TRUE;
volatile HWND hMasterKey = NULL; /* Text box showing hex dump of the master key */
volatile HWND hHeaderKey = NULL; /* Text box showing hex dump of the header key */
volatile HWND hRandPool = NULL; /* Text box showing hex dump of the random pool */
volatile HWND hRandPoolSys = NULL; /* Text box showing hex dump of the random pool for system encryption */
volatile HWND hPasswordInputField = NULL; /* Password input field */
volatile HWND hVerifyPasswordInputField = NULL; /* Verify-password input field */
HBITMAP hbmWizardBitmapRescaled = NULL;
char OrigKeyboardLayout [8+1] = "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. */
#ifndef _DEBUG
BOOL bWarnDeviceFormatAdvanced = TRUE;
#else
BOOL bWarnDeviceFormatAdvanced = FALSE;
#endif
BOOL bWarnOuterVolSuitableFileSys = TRUE;
Password volumePassword; /* User password */
char szVerify[MAX_PASSWORD + 1]; /* Tmp password buffer */
char szRawPassword[MAX_PASSWORD + 1]; /* Password before keyfile was applied to it */
BOOL bHistoryCmdLine = FALSE; /* History control is always disabled */
BOOL ComServerMode = FALSE;
int nPbar = 0; /* Control ID of progress bar:- for format code */
char HeaderKeyGUIView [KEY_GUI_VIEW_SIZE];
char MasterKeyGUIView [KEY_GUI_VIEW_SIZE];
#define RANDPOOL_DISPLAY_COLUMNS 15
#define RANDPOOL_DISPLAY_ROWS 8
#define RANDPOOL_DISPLAY_BYTE_PORTION (RANDPOOL_DISPLAY_COLUMNS * RANDPOOL_DISPLAY_ROWS)
#define RANDPOOL_DISPLAY_SIZE (RANDPOOL_DISPLAY_BYTE_PORTION * 3 + RANDPOOL_DISPLAY_ROWS + 2)
unsigned char randPool [RANDPOOL_DISPLAY_BYTE_PORTION];
unsigned char lastRandPool [RANDPOOL_DISPLAY_BYTE_PORTION];
unsigned char outRandPoolDispBuffer [RANDPOOL_DISPLAY_SIZE];
BOOL bDisplayPoolContents = TRUE;
volatile BOOL bSparseFileSwitch = FALSE;
volatile BOOL quickFormat = FALSE; /* WARNING: Meaning of this variable depends on bSparseFileSwitch. If bSparseFileSwitch is TRUE, this variable represents the sparse file flag. */
volatile int fileSystem = FILESYS_NONE;
volatile int clusterSize = 0;
SYSENC_MULTIBOOT_CFG SysEncMultiBootCfg;
wchar_t SysEncMultiBootCfgOutcome [4096] = {'N','/','A',0};
volatile int NonSysInplaceEncStatus = NONSYS_INPLACE_ENC_STATUS_NONE;
vector <HostDevice> DeferredNonSysInPlaceEncDevices;
static BOOL ElevateWholeWizardProcess (string arguments)
{
char modPath[MAX_PATH];
if (IsAdmin())
return TRUE;
if (!IsUacSupported())
return IsAdmin();
GetModuleFileName (NULL, modPath, sizeof (modPath));
if ((int)ShellExecute (MainDlg, "runas", modPath, (string("/q UAC ") + arguments).c_str(), NULL, SW_SHOWNORMAL) > 32)
{
exit (0);
}
else
{
Error ("UAC_INIT_ERROR");
return FALSE;
}
}
static void WipePasswordsAndKeyfiles (void)
{
char tmp[MAX_PASSWORD+1];
// Attempt to wipe passwords stored in the input field buffers
memset (tmp, 'X', MAX_PASSWORD);
tmp [MAX_PASSWORD] = 0;
SetWindowText (hPasswordInputField, tmp);
SetWindowText (hVerifyPasswordInputField, tmp);
burn (&szVerify[0], sizeof (szVerify));
burn (&volumePassword, sizeof (volumePassword));
burn (&szRawPassword[0], sizeof (szRawPassword));
SetWindowText (hPasswordInputField, "");
SetWindowText (hVerifyPasswordInputField, "");
KeyFileRemoveAll (&FirstKeyFile);
KeyFileRemoveAll (&defaultKeyFilesParam.FirstKeyFile);
}
static void localcleanup (void)
{
char tmp[RANDPOOL_DISPLAY_SIZE+1];
// System encryption
if (WizardMode == WIZARD_MODE_SYS_DEVICE
&& InstanceHasSysEncMutex ())
{
try
{
BootEncStatus = BootEncObj->GetStatus();
if (BootEncStatus.SetupInProgress)
{
BootEncObj->AbortSetup ();
}
}
catch (...)
{
// NOP
}
}
// Mon-system in-place encryption
if (bInPlaceEncNonSys && (bVolTransformThreadRunning || bVolTransformThreadToRun))
{
NonSysInplaceEncPause ();
}
CloseNonSysInplaceEncMutex ();
// Device wipe
if (bDeviceWipeInProgress)
WipeAbort();
WipePasswordsAndKeyfiles ();
RandStop (TRUE);
burn (HeaderKeyGUIView, sizeof(HeaderKeyGUIView));
burn (MasterKeyGUIView, sizeof(MasterKeyGUIView));
burn (randPool, sizeof(randPool));
burn (lastRandPool, sizeof(lastRandPool));
burn (outRandPoolDispBuffer, sizeof(outRandPoolDispBuffer));
burn (szFileName, sizeof(szFileName));
burn (szDiskFile, sizeof(szDiskFile));
// Attempt to wipe the GUI fields showing portions of randpool, of the master and header keys
memset (tmp, 'X', sizeof(tmp));
tmp [sizeof(tmp)-1] = 0;
SetWindowText (hRandPool, tmp);
SetWindowText (hRandPoolSys, tmp);
SetWindowText (hMasterKey, tmp);
SetWindowText (hHeaderKey, tmp);
UnregisterRedTick (hInst);
// Delete buffered bitmaps (if any)
if (hbmWizardBitmapRescaled != NULL)
{
DeleteObject ((HGDIOBJ) hbmWizardBitmapRescaled);
hbmWizardBitmapRescaled = NULL;
}
// Cleanup common code resources
cleanup ();
if (BootEncObj != NULL)
{
delete BootEncObj;
BootEncObj = NULL;
}
}
static BOOL CALLBACK BroadcastSysEncCfgUpdateCallb (HWND hwnd, LPARAM lParam)
{
if (GetWindowLongPtr (hwnd, GWLP_USERDATA) == (LONG_PTR) 'TRUE')
{
char name[1024] = { 0 };
GetWindowText (hwnd, name, sizeof (name) - 1);
if (hwnd != MainDlg && strstr (name, "TrueCrypt"))
{
PostMessage (hwnd, TC_APPMSG_SYSENC_CONFIG_UPDATE, 0, 0);
}
}
return TRUE;
}
static BOOL BroadcastSysEncCfgUpdate (void)
{
BOOL bSuccess = FALSE;
EnumWindows (BroadcastSysEncCfgUpdateCallb, (LPARAM) &bSuccess);
return bSuccess;
}
// IMPORTANT: This function may be called only by Format (other modules can only _read_ the system encryption config).
// Returns TRUE if successful (otherwise FALSE)
static BOOL SaveSysEncSettings (HWND hwndDlg)
{
FILE *f;
if (!bSystemEncryptionStatusChanged)
return TRUE;
if (hwndDlg == NULL && MainDlg != NULL)
hwndDlg = MainDlg;
if (!CreateSysEncMutex ())
return FALSE; // Only one instance that has the mutex can modify the system encryption settings
if (SystemEncryptionStatus == SYSENC_STATUS_NONE)
{
if (remove (GetConfigPath (TC_APPD_FILENAME_SYSTEM_ENCRYPTION)) != 0)
{
Error ("CANNOT_SAVE_SYS_ENCRYPTION_SETTINGS");
return FALSE;
}
bSystemEncryptionStatusChanged = FALSE;
BroadcastSysEncCfgUpdate ();
return TRUE;
}
f = fopen (GetConfigPath (TC_APPD_FILENAME_SYSTEM_ENCRYPTION), "w");
if (f == NULL)
{
Error ("CANNOT_SAVE_SYS_ENCRYPTION_SETTINGS");
handleWin32Error (hwndDlg);
return FALSE;
}
if (XmlWriteHeader (f) < 0
|| fputs ("\n\t<sysencryption>", f) < 0
|| fprintf (f, "\n\t\t<config key=\"SystemEncryptionStatus\">%d</config>", SystemEncryptionStatus) < 0
|| fprintf (f, "\n\t\t<config key=\"WipeMode\">%d</config>", (int) nWipeMode) < 0
|| fputs ("\n\t</sysencryption>", f) < 0
|| XmlWriteFooter (f) < 0)
{
handleWin32Error (hwndDlg);
fclose (f);
Error ("CANNOT_SAVE_SYS_ENCRYPTION_SETTINGS");
return FALSE;
}
TCFlushFile (f);
fclose (f);
bSystemEncryptionStatusChanged = FALSE;
BroadcastSysEncCfgUpdate ();
return TRUE;
}
// WARNING: This function may take a long time to finish
static unsigned int DetermineHiddenOSCreationPhase (void)
{
unsigned int phase = TC_HIDDEN_OS_CREATION_PHASE_NONE;
try
{
phase = BootEncObj->GetHiddenOSCreationPhase();
}
catch (Exception &e)
{
e.Show (MainDlg);
AbortProcess("ERR_GETTING_SYSTEM_ENCRYPTION_STATUS");
}
return phase;
}
// IMPORTANT: This function may be called only by Format (other modules can only _read_ the status).
// Returns TRUE if successful (otherwise FALSE)
static BOOL ChangeHiddenOSCreationPhase (int newPhase)
{
if (!CreateSysEncMutex ())
{
Error ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE");
return FALSE;
}
try
{
BootEncObj->SetHiddenOSCreationPhase (newPhase);
}
catch (Exception &e)
{
e.Show (MainDlg);
return FALSE;
}
//// The contents of the following items might be inappropriate after a change of the phase
//szFileName[0] = 0;
//szDiskFile[0] = 0;
//nUIVolumeSize = 0;
//nVolumeSize = 0;
return TRUE;
}
// IMPORTANT: This function may be called only by Format (other modules can only _read_ the system encryption status).
// Returns TRUE if successful (otherwise FALSE)
static BOOL ChangeSystemEncryptionStatus (int newStatus)
{
if (!CreateSysEncMutex ())
{
Error ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE");
return FALSE; // Only one instance that has the mutex can modify the system encryption settings
}
SystemEncryptionStatus = newStatus;
bSystemEncryptionStatusChanged = TRUE;
if (newStatus == SYSENC_STATUS_ENCRYPTING)
{
// If the user has created a hidden OS and now is creating a decoy OS, we must wipe the hidden OS
// config area in the MBR.
WipeHiddenOSCreationConfig();
}
if (newStatus == SYSENC_STATUS_NONE && !IsHiddenOSRunning())
{
if (DetermineHiddenOSCreationPhase() != TC_HIDDEN_OS_CREATION_PHASE_NONE
&& !ChangeHiddenOSCreationPhase (TC_HIDDEN_OS_CREATION_PHASE_NONE))
return FALSE;
WipeHiddenOSCreationConfig();
}
if (!SaveSysEncSettings (MainDlg))
{
return FALSE;
}
return TRUE;
}
// If the return code of this function is ignored and newWizardMode == WIZARD_MODE_SYS_DEVICE, then this function
// may be called only after CreateSysEncMutex() returns TRUE. It returns TRUE if successful (otherwise FALSE).
static BOOL ChangeWizardMode (int newWizardMode)
{
if (WizardMode != newWizardMode)
{
if (WizardMode == WIZARD_MODE_SYS_DEVICE || newWizardMode == WIZARD_MODE_SYS_DEVICE)
{
if (newWizardMode == WIZARD_MODE_SYS_DEVICE)
{
if (!CreateSysEncMutex ())
{
Error ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE");
return FALSE;
}
}
// If the previous mode was different, the password may have been typed using a different
// keyboard layout (which might confuse the user and cause other problems if system encryption
// was or will be involved).
WipePasswordsAndKeyfiles();
}
if (newWizardMode != WIZARD_MODE_NONSYS_DEVICE)
bInPlaceEncNonSys = FALSE;
if (newWizardMode == WIZARD_MODE_NONSYS_DEVICE && !IsAdmin() && IsUacSupported())
{
if (!ElevateWholeWizardProcess ("/e"))
return FALSE;
}
// The contents of the following items may be inappropriate after a change of mode
szFileName[0] = 0;
szDiskFile[0] = 0;
nUIVolumeSize = 0;
nVolumeSize = 0;
WizardMode = newWizardMode;
}
bDevice = (WizardMode != WIZARD_MODE_FILE_CONTAINER);
if (newWizardMode != WIZARD_MODE_SYS_DEVICE
&& !bHiddenOS)
{
CloseSysEncMutex ();
}
return TRUE;
}
// Determines whether the wizard directly affects system encryption in any way.
// Note, for example, that when the user enters a password for a hidden volume that is to host a hidden OS,
// WizardMode is NOT set to WIZARD_MODE_SYS_DEVICE. The keyboard layout, however, has to be US. That's why
// this function has to be called instead of checking the value of WizardMode.
static BOOL SysEncInEffect (void)
{
return (WizardMode == WIZARD_MODE_SYS_DEVICE
|| CreatingHiddenSysVol());
}
static BOOL CreatingHiddenSysVol (void)
{
return (bHiddenOS
&& bHiddenVol && !bHiddenVolHost);
}
static void LoadSettings (HWND hwndDlg)
{
EnableHwEncryption ((ReadDriverConfigurationFlags() & TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION) ? FALSE : TRUE);
WipeAlgorithmId savedWipeAlgorithm = TC_WIPE_NONE;
LoadSysEncSettings (hwndDlg);
if (LoadNonSysInPlaceEncSettings (&savedWipeAlgorithm) != 0)
bInPlaceEncNonSysPending = TRUE;
defaultKeyFilesParam.EnableKeyFiles = FALSE;
bStartOnLogon = ConfigReadInt ("StartOnLogon", FALSE);
HiddenSectorDetectionStatus = ConfigReadInt ("HiddenSectorDetectionStatus", 0);
bHistory = ConfigReadInt ("SaveVolumeHistory", FALSE);
ConfigReadString ("SecurityTokenLibrary", "", SecurityTokenLibraryPath, sizeof (SecurityTokenLibraryPath) - 1);
if (SecurityTokenLibraryPath[0])
InitSecurityTokenLibrary();
if (hwndDlg != NULL)
{
LoadCombo (GetDlgItem (hwndDlg, IDC_COMBO_BOX));
return;
}
if (bHistoryCmdLine)
return;
}
static void SaveSettings (HWND hwndDlg)
{
WaitCursor ();
if (hwndDlg != NULL)
DumpCombo (GetDlgItem (hwndDlg, IDC_COMBO_BOX), !bHistory);
ConfigWriteBegin ();
ConfigWriteInt ("StartOnLogon", bStartOnLogon);
ConfigWriteInt ("HiddenSectorDetectionStatus", HiddenSectorDetectionStatus);
ConfigWriteInt ("SaveVolumeHistory", bHistory);
ConfigWriteString ("SecurityTokenLibrary", SecurityTokenLibraryPath[0] ? SecurityTokenLibraryPath : "");
if (GetPreferredLangId () != NULL)
ConfigWriteString ("Language", GetPreferredLangId ());
ConfigWriteEnd ();
NormalCursor ();
}
// WARNING: This function does NOT cause immediate application exit (use e.g. return 1 after calling it
// from a DialogProc function).
static void EndMainDlg (HWND hwndDlg)
{
if (nCurPageNo == VOLUME_LOCATION_PAGE)
{
if (IsWindow(GetDlgItem(hCurPage, IDC_NO_HISTORY)))
bHistory = !IsButtonChecked (GetDlgItem (hCurPage, IDC_NO_HISTORY));
MoveEditToCombo (GetDlgItem (hCurPage, IDC_COMBO_BOX), bHistory);
SaveSettings (hCurPage);
}
else
{
SaveSettings (NULL);
}
SaveSysEncSettings (hwndDlg);
if (!bHistory)
CleanLastVisitedMRU ();
EndDialog (hwndDlg, 0);
}
// Returns TRUE if system encryption or decryption had been or is in progress and has not been completed
static BOOL SysEncryptionOrDecryptionRequired (void)
{
/* If you update this function, revise SysEncryptionOrDecryptionRequired() in Mount.c as well. */
static BootEncryptionStatus locBootEncStatus;
try
{
locBootEncStatus = BootEncObj->GetStatus();
}
catch (Exception &e)
{
e.Show (MainDlg);
}
return (SystemEncryptionStatus == SYSENC_STATUS_ENCRYPTING
|| SystemEncryptionStatus == SYSENC_STATUS_DECRYPTING
||
(
locBootEncStatus.DriveMounted
&&
(
locBootEncStatus.ConfiguredEncryptedAreaStart != locBootEncStatus.EncryptedAreaStart
|| locBootEncStatus.ConfiguredEncryptedAreaEnd != locBootEncStatus.EncryptedAreaEnd
)
)
);
}
// Returns TRUE if the system partition/drive is completely encrypted
static BOOL SysDriveOrPartitionFullyEncrypted (BOOL bSilent)
{
/* If you update this function, revise SysDriveOrPartitionFullyEncrypted() in Mount.c as well. */
static BootEncryptionStatus locBootEncStatus;
try
{
locBootEncStatus = BootEncObj->GetStatus();
}
catch (Exception &e)
{
if (!bSilent)
e.Show (MainDlg);
}
return (!locBootEncStatus.SetupInProgress
&& locBootEncStatus.ConfiguredEncryptedAreaEnd != 0
&& locBootEncStatus.ConfiguredEncryptedAreaEnd != -1
&& locBootEncStatus.ConfiguredEncryptedAreaStart == locBootEncStatus.EncryptedAreaStart
&& locBootEncStatus.ConfiguredEncryptedAreaEnd == locBootEncStatus.EncryptedAreaEnd);
}
// This functions is to be used when the wizard mode needs to be changed to WIZARD_MODE_SYS_DEVICE.
// If the function fails to switch the mode, it returns FALSE (otherwise TRUE).
BOOL SwitchWizardToSysEncMode (void)
{
WaitCursor ();
try
{
BootEncStatus = BootEncObj->GetStatus();
bWholeSysDrive = BootEncObj->SystemPartitionCoversWholeDrive();
}
catch (Exception &e)
{
e.Show (MainDlg);
Error ("ERR_GETTING_SYSTEM_ENCRYPTION_STATUS");
NormalCursor ();
return FALSE;
}
// From now on, we should be the only instance of the TC wizard allowed to deal with system encryption
if (!CreateSysEncMutex ())
{
Warning ("SYSTEM_ENCRYPTION_IN_PROGRESS_ELSEWHERE");
NormalCursor ();
return FALSE;
}
// User-mode app may have crashed and its mutex may have gotten lost, so we need to check the driver status too
if (BootEncStatus.SetupInProgress)
{
if (AskWarnYesNo ("SYSTEM_ENCRYPTION_RESUME_PROMPT") == IDYES)
{
if (SystemEncryptionStatus != SYSENC_STATUS_ENCRYPTING
&& SystemEncryptionStatus != SYSENC_STATUS_DECRYPTING)
{
// The config file with status was lost or not written correctly
if (!ResolveUnknownSysEncDirection ())
{
CloseSysEncMutex ();
NormalCursor ();
return FALSE;
}
}
bDirectSysEncMode = TRUE;
ChangeWizardMode (WIZARD_MODE_SYS_DEVICE);
LoadPage (MainDlg, SYSENC_ENCRYPTION_PAGE);
NormalCursor ();
return TRUE;
}
else
{
CloseSysEncMutex ();
Error ("SYS_ENCRYPTION_OR_DECRYPTION_IN_PROGRESS");
NormalCursor ();
return FALSE;
}
}
if (BootEncStatus.DriveMounted
|| BootEncStatus.DriveEncrypted
|| SysEncryptionOrDecryptionRequired ())
{
if (!SysDriveOrPartitionFullyEncrypted (FALSE)
&& AskWarnYesNo ("SYSTEM_ENCRYPTION_RESUME_PROMPT") == IDYES)
{
if (SystemEncryptionStatus == SYSENC_STATUS_NONE)
{
// If the config file with status was lost or not written correctly, we
// don't know whether to encrypt or decrypt (but we know that encryption or
// decryption is required). Ask the user to select encryption, decryption,
// or cancel
if (!ResolveUnknownSysEncDirection ())
{
CloseSysEncMutex ();
NormalCursor ();
return FALSE;
}
}
bDirectSysEncMode = TRUE;
ChangeWizardMode (WIZARD_MODE_SYS_DEVICE);
LoadPage (MainDlg, SYSENC_ENCRYPTION_PAGE);
NormalCursor ();
return TRUE;
}
else
{
CloseSysEncMutex ();
Error ("SETUP_FAILED_BOOT_DRIVE_ENCRYPTED");
NormalCursor ();
return FALSE;
}
}
else
{
// Check compliance with requirements for boot encryption
if (!IsAdmin())
{
if (!IsUacSupported())
{
Warning ("ADMIN_PRIVILEGES_WARN_DEVICES");
}
}
try
{
BootEncObj->CheckRequirements ();
}
catch (Exception &e)
{
CloseSysEncMutex ();
e.Show (MainDlg);
NormalCursor ();
return FALSE;
}
if (!ChangeWizardMode (WIZARD_MODE_SYS_DEVICE))
{
NormalCursor ();
return FALSE;
}
if (bSysDriveSelected || bSysPartitionSelected)
{
// The user selected the non-sys-device wizard mode but then selected a system device
bWholeSysDrive = (bSysDriveSelected && !bSysPartitionSelected);
bSysDriveSelected = FALSE;
bSysPartitionSelected = FALSE;
try
{
if (!bHiddenVol)
{
if (bWholeSysDrive && !BootEncObj->SystemPartitionCoversWholeDrive())
{
if (BootEncObj->SystemDriveContainsNonStandardPartitions())
{
if (AskWarnYesNoString ((wstring (GetString ("SYSDRIVE_NON_STANDARD_PARTITIONS")) + L"\n\n" + GetString ("ASK_ENCRYPT_PARTITION_INSTEAD_OF_DRIVE")).c_str()) == IDYES)
bWholeSysDrive = FALSE;
}
if (!IsOSAtLeast (WIN_VISTA) && bWholeSysDrive)
{
if (BootEncObj->SystemDriveContainsExtendedPartition())
{
bWholeSysDrive = FALSE;
Error ("WDE_UNSUPPORTED_FOR_EXTENDED_PARTITIONS");
if (AskYesNo ("ASK_ENCRYPT_PARTITION_INSTEAD_OF_DRIVE") == IDNO)
{
ChangeWizardMode (WIZARD_MODE_NONSYS_DEVICE);
return FALSE;
}
}
else
Warning ("WDE_EXTENDED_PARTITIONS_WARNING");
}
}
else if (BootEncObj->SystemPartitionCoversWholeDrive()
&& !bWholeSysDrive)
bWholeSysDrive = (AskYesNo ("WHOLE_SYC_DEVICE_RECOM") == IDYES);
}
}
catch (Exception &e)
{
e.Show (MainDlg);
return FALSE;
}
if (!bHiddenVol)
{
// Skip SYSENC_SPAN_PAGE and SYSENC_TYPE_PAGE as the user already made the choice
LoadPage (MainDlg, bWholeSysDrive ? SYSENC_PRE_DRIVE_ANALYSIS_PAGE : SYSENC_MULTI_BOOT_MODE_PAGE);
}
else
{
// The user selected the non-sys-device wizard mode but then selected a system device.
// In addition, he selected the hidden volume mode.
if (bWholeSysDrive)
Warning ("HIDDEN_OS_PRECLUDES_SINGLE_KEY_WDE");
bWholeSysDrive = FALSE;
LoadPage (MainDlg, SYSENC_TYPE_PAGE);
}
}
else
LoadPage (MainDlg, SYSENC_TYPE_PAGE);
NormalCursor ();
return TRUE;
}
}
void SwitchWizardToFileContainerMode (void)
{
ChangeWizardMode (WIZARD_MODE_FILE_CONTAINER);
LoadPage (MainDlg, VOLUME_LOCATION_PAGE);
NormalCursor ();
}
void SwitchWizardToNonSysDeviceMode (void)
{
ChangeWizardMode (WIZARD_MODE_NONSYS_DEVICE);
LoadPage (MainDlg, VOLUME_TYPE_PAGE);
NormalCursor ();
}
BOOL SwitchWizardToHiddenOSMode (void)
{
if (SwitchWizardToSysEncMode())
{
if (nCurPageNo != SYSENC_ENCRYPTION_PAGE) // If the user did not manually choose to resume encryption or decryption of the system partition/drive
{
bHiddenOS = TRUE;
bHiddenVol = TRUE;
bHiddenVolHost = TRUE;
bHiddenVolDirect = FALSE;
bWholeSysDrive = FALSE;
bInPlaceEncNonSys = FALSE;
if (bDirectSysEncModeCommand == SYSENC_COMMAND_CREATE_HIDDEN_OS_ELEV)
{
// Some of the requirements for hidden OS should have already been checked by the wizard process
// that launched us (in order to elevate), but we must recheck them. Otherwise, an advanced user
// could bypass the checks by using the undocumented CLI switch. Moreover, some requirements
// can be checked only at this point (when we are elevated).
try
{
BootEncObj->CheckRequirementsHiddenOS ();
BootEncObj->InitialSecurityChecksForHiddenOS ();
}
catch (Exception &e)
{
e.Show (MainDlg);
return FALSE;
}
LoadPage (MainDlg, SYSENC_MULTI_BOOT_MODE_PAGE);
}
else