forked from veracrypt/VeraCrypt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDlgcode.c
More file actions
16482 lines (13481 loc) · 446 KB
/
Dlgcode.c
File metadata and controls
16482 lines (13481 loc) · 446 KB
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 TrueCrypt 7.1a, which is
Copyright (c) 2003-2012 TrueCrypt Developers Association and which is
governed by the TrueCrypt License 3.0, also from the source code of
Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux
and which is governed by the 'License Agreement for Encryption for the Masses'
Modifications and additions to the original source code (contained in this file)
and all other portions of this file are Copyright (c) 2013-2025 AM Crypto
and are governed by the Apache License 2.0 the full text of which is
contained in the file License.txt included in VeraCrypt binary and source
code distribution packages. */
#include "Tcdefs.h"
#include <windowsx.h>
#include <versionhelpers.h>
#include <dbghelp.h>
#include <dbt.h>
#include <Setupapi.h>
#include <aclapi.h>
#include <Netlistmgr.h>
#include <fcntl.h>
#include <io.h>
#include <math.h>
#include <shlobj.h>
#include <shlwapi.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <time.h>
#include <tchar.h>
#include <Richedit.h>
#if defined (TCMOUNT) || defined (VOLFORMAT)
#include <process.h>
#include <Tlhelp32.h>
#endif
#if _WIN32_WINNT >= 0x0602
#include "processthreadsapi.h"
#endif
#include "Resource.h"
#include "Platform/Finally.h"
#include "Platform/ForEach.h"
#include "Apidrvr.h"
#include "BootEncryption.h"
#include "Combo.h"
#include "Crc.h"
#include "Crypto.h"
#include "Dictionary.h"
#include "Dlgcode.h"
#include "EncryptionThreadPool.h"
#include "Endian.h"
#include "Format/Inplace.h"
#include "Language.h"
#include "Keyfiles.h"
#include "Pkcs5.h"
#include "Random.h"
#include "Registry.h"
#include "SecurityToken.h"
#include "Tests.h"
#include "Volumes.h"
#include "Wipe.h"
#include "Xml.h"
#include "Xts.h"
#include "Boot/Windows/BootCommon.h"
#include "Progress.h"
#include "zip.h"
#include "rdrand.h"
#include "jitterentropy.h"
#ifdef TCMOUNT
#include "Mount/Mount.h"
#include "Mount/resource.h"
#endif
#ifdef VOLFORMAT
#include "Format/Tcformat.h"
#endif
#ifdef SETUP
#include "Setup/Setup.h"
#endif
#include <Setupapi.h>
#include <Softpub.h>
#include <WinTrust.h>
#include <strsafe.h>
#define _WIN32_DCOM
#include <comdef.h>
#include <Wbemidl.h>
#pragma comment(lib, "wbemuuid.lib")
#pragma comment(lib, "Shlwapi.lib")
#pragma comment(lib, "setupapi.lib" )
#pragma comment(lib, "Wintrust.lib" )
#pragma comment(lib, "Comctl32.lib" )
#ifndef TTI_INFO_LARGE
#define TTI_INFO_LARGE 4
#endif
#ifndef TTI_WARNING_LARGE
#define TTI_WARNING_LARGE 5
#endif
#ifndef TTI_ERROR_LARGE
#define TTI_ERROR_LARGE 6
#endif
/* GPT Partition Type GUIDs */
#define LOCAL_DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) const GUID name = {l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8}
LOCAL_DEFINE_GUID(PARTITION_ENTRY_UNUSED_GUID, 0x00000000L, 0x0000, 0x0000, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00); // Entry unused
LOCAL_DEFINE_GUID(PARTITION_SYSTEM_GUID, 0xC12A7328L, 0xF81F, 0x11D2, 0xBA, 0x4B, 0x00, 0xA0, 0xC9, 0x3E, 0xC9, 0x3B); // EFI system partition
LOCAL_DEFINE_GUID(PARTITION_MSFT_RESERVED_GUID, 0xE3C9E316L, 0x0B5C, 0x4DB8, 0x81, 0x7D, 0xF9, 0x2D, 0xF0, 0x02, 0x15, 0xAE); // Microsoft reserved space
LOCAL_DEFINE_GUID(PARTITION_BASIC_DATA_GUID, 0xEBD0A0A2L, 0xB9E5, 0x4433, 0x87, 0xC0, 0x68, 0xB6, 0xB7, 0x26, 0x99, 0xC7); // Basic data partition
LOCAL_DEFINE_GUID(PARTITION_LDM_METADATA_GUID, 0x5808C8AAL, 0x7E8F, 0x42E0, 0x85, 0xD2, 0xE1, 0xE9, 0x04, 0x34, 0xCF, 0xB3); // Logical Disk Manager metadata partition
LOCAL_DEFINE_GUID(PARTITION_LDM_DATA_GUID, 0xAF9B60A0L, 0x1431, 0x4F62, 0xBC, 0x68, 0x33, 0x11, 0x71, 0x4A, 0x69, 0xAD); // Logical Disk Manager data partition
LOCAL_DEFINE_GUID(PARTITION_MSFT_RECOVERY_GUID, 0xDE94BBA4L, 0x06D1, 0x4D40, 0xA1, 0x6A, 0xBF, 0xD5, 0x01, 0x79, 0xD6, 0xAC); // Microsoft recovery partition
LOCAL_DEFINE_GUID(PARTITION_CLUSTER_GUID, 0xdb97dba9L, 0x0840, 0x4bae, 0x97, 0xf0, 0xff, 0xb9, 0xa3, 0x27, 0xc7, 0xe1); // Cluster metadata partition
#ifndef PROCESSOR_ARCHITECTURE_ARM64
#define PROCESSOR_ARCHITECTURE_ARM64 12
#endif
#ifndef IMAGE_FILE_MACHINE_ARM64
#define IMAGE_FILE_MACHINE_ARM64 0xAA64
#endif
using namespace VeraCrypt;
LONG DriverVersion;
char *LastDialogId;
wchar_t szHelpFile[TC_MAX_PATH];
wchar_t szHelpFile2[TC_MAX_PATH];
wchar_t SecurityTokenLibraryPath[TC_MAX_PATH];
char CmdTokenPin [TC_MAX_PATH] = {0};
HFONT hFixedDigitFont = NULL;
HFONT hBoldFont = NULL;
HFONT hTitleFont = NULL;
HFONT hFixedFont = NULL;
HFONT hUserFont = NULL;
HFONT hUserUnderlineFont = NULL;
HFONT hUserBoldFont = NULL;
HFONT hUserUnderlineBoldFont = NULL;
HFONT WindowTitleBarFont;
WCHAR EditPasswordChar = 0;
int ScreenDPI = USER_DEFAULT_SCREEN_DPI;
double DPIScaleFactorX = 1;
double DPIScaleFactorY = 1;
double DlgAspectRatio = 1;
HWND MainDlg = NULL;
wchar_t *lpszTitle = NULL;
BOOL Silent = FALSE;
BOOL bPreserveTimestamp = TRUE;
BOOL bShowDisconnectedNetworkDrives = FALSE;
BOOL bHideWaitingDialog = FALSE;
BOOL bCmdHideWaitingDialog = FALSE;
BOOL bCmdHideWaitingDialogValid = FALSE;
BOOL bUseSecureDesktop = FALSE;
BOOL bEnableIMEInSecureDesktop = FALSE;
BOOL bUseLegacyMaxPasswordLength = FALSE;
BOOL bCmdUseSecureDesktop = FALSE;
BOOL bCmdUseSecureDesktopValid = FALSE;
BOOL bCmdEnableIMEInSecureDesktop = FALSE;
BOOL bCmdEnableIMEInSecureDesktopValid = FALSE;
BOOL bStartOnLogon = FALSE;
BOOL bMountDevicesOnLogon = FALSE;
BOOL bMountFavoritesOnLogon = FALSE;
BOOL bHistory = FALSE;
#ifndef SETUP
BOOL bLanguageSetInSetup = FALSE;
#else
extern BOOL bMakePackage;
#endif
#ifdef TCMOUNT
extern BOOL ServiceMode;
#endif
// Status of detection of hidden sectors (whole-system-drive encryption).
// 0 - Unknown/undetermined/completed, 1: Detection is or was in progress (but did not complete e.g. due to system crash).
int HiddenSectorDetectionStatus = 0;
OSVersionEnum nCurrentOS = WIN_UNKNOWN;
int CurrentOSMajor = 0;
int CurrentOSMinor = 0;
int CurrentOSServicePack = 0;
int CurrentOSBuildNumber = 0;
BOOL RemoteSession = FALSE;
BOOL UacElevated = FALSE;
BOOL bPortableModeConfirmed = FALSE; // TRUE if it is certain that the instance is running in portable mode
BOOL bInPlaceEncNonSysPending = FALSE; // TRUE if the non-system in-place encryption config file indicates that one or more partitions are scheduled to be encrypted. This flag is set only when config files are loaded during app startup.
/* Globals used by Mount and Format (separately per instance) */
BOOL PimEnable = FALSE;
BOOL KeyFilesEnable = FALSE;
KeyFile *FirstKeyFile = NULL;
KeyFilesDlgParam defaultKeyFilesParam = {0};
BOOL IgnoreWmDeviceChange = FALSE;
BOOL DeviceChangeBroadcastDisabled = FALSE;
BOOL LastMountedVolumeDirty;
BOOL MountVolumesAsSystemFavorite = FALSE;
BOOL FavoriteMountOnArrivalInProgress = FALSE;
BOOL MultipleMountOperationInProgress = FALSE;
BOOL EMVSupportEnabled = FALSE;
volatile BOOL NeedPeriodicDeviceListUpdate = FALSE;
BOOL DisablePeriodicDeviceListUpdate = FALSE;
BOOL EnableMemoryProtection = FALSE;
BOOL EnableScreenProtection = FALSE;
BOOL MemoryProtectionActivated = FALSE;
BOOL WaitDialogDisplaying = FALSE;
/* Handle to the device driver */
HANDLE hDriver = INVALID_HANDLE_VALUE;
/* This mutex is used to prevent multiple instances of the wizard or main app from dealing with system encryption */
volatile HANDLE hSysEncMutex = NULL;
/* This mutex is used for non-system in-place encryption but only for informative (non-blocking) purposes,
such as whether an app should prompt the user whether to resume scheduled process. */
volatile HANDLE hNonSysInplaceEncMutex = NULL;
/* This mutex is used to prevent multiple instances of the wizard or main app from trying to install or
register the driver or from trying to launch it in portable mode at the same time. */
volatile HANDLE hDriverSetupMutex = NULL;
/* This mutex is used to prevent users from running the main TrueCrypt app or the wizard while an instance
of the TrueCrypt installer is running (which is also useful for enforcing restart before the apps can be used). */
volatile HANDLE hAppSetupMutex = NULL;
/* Critical section used to protect access to global variables used in WNetGetConnection calls */
CRITICAL_SECTION csWNetCalls;
/* Critical section used to protect access to global list of physical drives */
CRITICAL_SECTION csMountableDevices;
CRITICAL_SECTION csVolumeIdCandidates;
static std::vector<HostDevice> mountableDevices;
static std::vector<HostDevice> rawHostDeviceList;
/* Critical section used to ensure that only one thread at a time can create a secure desktop */
CRITICAL_SECTION csSecureDesktop;
/* Boolean that indicates if our Secure Desktop is active and being used or not */
volatile BOOL bSecureDesktopOngoing = FALSE;
TCHAR SecureDesktopName[65];
HINSTANCE hInst = NULL;
HCURSOR hCursor = NULL;
ATOM hDlgClass, hSplashClass;
/* This value may changed only by calling ChangeSystemEncryptionStatus(). Only the wizard can change it
(others may still read it though). */
int SystemEncryptionStatus = SYSENC_STATUS_NONE;
/* Only the wizard can change this value (others may only read it). */
WipeAlgorithmId nWipeMode = TC_WIPE_NONE;
BOOL bSysPartitionSelected = FALSE; /* TRUE if the user selected the system partition via the Select Device dialog */
BOOL bSysDriveSelected = FALSE; /* TRUE if the user selected the system drive via the Select Device dialog */
/* To populate these arrays, call GetSysDevicePaths(). If they contain valid paths, bCachedSysDevicePathsValid is TRUE. */
wchar_t SysPartitionDevicePath [TC_MAX_PATH];
wchar_t SysDriveDevicePath [TC_MAX_PATH];
wstring ExtraBootPartitionDevicePath;
char bCachedSysDevicePathsValid = FALSE;
BOOL bHyperLinkBeingTracked = FALSE;
int WrongPwdRetryCounter = 0;
static FILE *ConfigFileHandle;
char *ConfigBuffer;
BOOL SystemFileSelectorCallPending = FALSE;
DWORD SystemFileSelectorCallerThreadId;
#define RANDPOOL_DISPLAY_REFRESH_INTERVAL 30
#define RANDPOOL_DISPLAY_ROWS 16
#define RANDPOOL_DISPLAY_COLUMNS 20
#ifndef LOAD_LIBRARY_SEARCH_SYSTEM32
#define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800
#endif
typedef BOOL (WINAPI *SetDefaultDllDirectoriesPtr)(DWORD DirectoryFlags);
static unsigned char gpbSha512CodeSignCertFingerprint[64] = {
0xDA, 0x24, 0x2D, 0x36, 0x88, 0xC1, 0x4A, 0x34, 0x53, 0x26, 0x9C, 0x65,
0x66, 0x24, 0xE3, 0xE7, 0xC5, 0xBA, 0x64, 0x68, 0xC7, 0x32, 0xAB, 0x4B,
0x06, 0xA8, 0x55, 0x98, 0xAD, 0x04, 0xFD, 0xFD, 0x31, 0xCE, 0x8D, 0xD1,
0xBF, 0x8C, 0x51, 0x5F, 0x8B, 0xF9, 0xC3, 0xCF, 0x32, 0x8B, 0xA9, 0x8A,
0x53, 0xCB, 0x7C, 0x4D, 0xF3, 0x15, 0x43, 0x2F, 0x2B, 0x71, 0x30, 0x2F,
0xF1, 0x08, 0xF3, 0xA8
};
static unsigned char gpbSha512MSCodeSignCertFingerprint[64] = {
0x17, 0x8C, 0x1B, 0x37, 0x70, 0xBF, 0x8B, 0xDF, 0x84, 0x55, 0xC5, 0x18,
0x13, 0x64, 0xE9, 0x65, 0x6D, 0x67, 0xCA, 0x0C, 0xD6, 0x3B, 0x9E, 0x7B,
0x9B, 0x6A, 0x63, 0xD6, 0x19, 0xAE, 0xD7, 0xBA, 0xBE, 0x5C, 0xCB, 0xD1,
0x07, 0x89, 0x07, 0xFB, 0x12, 0xC0, 0x2C, 0x94, 0x86, 0xEB, 0x67, 0x0B,
0x9C, 0x97, 0xEB, 0x20, 0x38, 0x13, 0x9C, 0x0F, 0x56, 0x93, 0x1B, 0x19,
0x6F, 0x8F, 0x6A, 0x39
};
/* Windows dialog class */
#define WINDOWS_DIALOG_CLASS L"#32770"
/* Custom class names */
#define TC_DLG_CLASS L"VeraCryptCustomDlg"
#define TC_SPLASH_CLASS L"VeraCryptSplashDlg"
/* constant used by ChangeWindowMessageFilter calls */
#ifndef MSGFLT_ADD
#define MSGFLT_ADD 1
#endif
/* undocumented message sent during drag-n-drop */
#ifndef WM_COPYGLOBALDATA
#define WM_COPYGLOBALDATA 0x0049
#endif
/* Benchmarks */
#ifndef SETUP
#define BENCHMARK_MAX_ITEMS 100
#define BENCHMARK_DEFAULT_BUF_SIZE BYTES_PER_MB
#define HASH_FNC_BENCHMARKS FALSE // For development purposes only. Must be FALSE when building a public release.
#define PKCS5_BENCHMARKS FALSE // For development purposes only. Must be FALSE when building a public release.
#if PKCS5_BENCHMARKS && HASH_FNC_BENCHMARKS
#error PKCS5_BENCHMARKS and HASH_FNC_BENCHMARKS are both TRUE (at least one of them should be FALSE).
#endif
enum
{
BENCHMARK_TYPE_ENCRYPTION = 0,
BENCHMARK_TYPE_PRF,
BENCHMARK_TYPE_HASH
};
enum
{
BENCHMARK_SORT_BY_NAME = 0,
BENCHMARK_SORT_BY_SPEED
};
typedef struct
{
int id;
wchar_t name[100];
unsigned __int64 encSpeed;
unsigned __int64 decSpeed;
unsigned __int64 meanBytesPerSec;
unsigned __int64 iterations;
unsigned __int64 memoryCost;
} BENCHMARK_REC;
BENCHMARK_REC benchmarkTable [BENCHMARK_MAX_ITEMS];
int benchmarkTotalItems = 0;
int benchmarkBufferSize = BENCHMARK_DEFAULT_BUF_SIZE;
int benchmarkLastBufferSize = BENCHMARK_DEFAULT_BUF_SIZE;
int benchmarkSortMethod = BENCHMARK_SORT_BY_SPEED;
LARGE_INTEGER benchmarkPerformanceFrequency;
int benchmarkType = BENCHMARK_TYPE_ENCRYPTION;
int benchmarkPim = -1;
BOOL benchmarkPreBoot = FALSE;
BOOL benchmarkGPT = FALSE;
#endif // #ifndef SETUP
typedef struct
{
void *strings;
BOOL bold;
} MULTI_CHOICE_DLGPROC_PARAMS;
// Loads a 32-bit integer from the file at the specified file offset. The saved value is assumed to have been
// processed by mputLong(). The result is stored in *result. Returns TRUE if successful (otherwise FALSE).
BOOL LoadInt32 (const wchar_t *filePath, unsigned __int32 *result, __int64 fileOffset)
{
DWORD bufSize = sizeof(__int32);
unsigned char *buffer = (unsigned char *) malloc (bufSize);
unsigned char *bufferPtr = buffer;
HANDLE src = NULL;
DWORD bytesRead;
LARGE_INTEGER seekOffset, seekOffsetNew;
BOOL retVal = FALSE;
if (buffer == NULL)
return -1;
src = CreateFile (filePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (src == INVALID_HANDLE_VALUE)
{
free (buffer);
return FALSE;
}
seekOffset.QuadPart = fileOffset;
if (SetFilePointerEx (src, seekOffset, &seekOffsetNew, FILE_BEGIN) == 0)
goto fsif_end;
if (ReadFile (src, buffer, bufSize, &bytesRead, NULL) == 0
|| bytesRead != bufSize)
goto fsif_end;
retVal = TRUE;
*result = mgetLong(bufferPtr);
fsif_end:
CloseHandle (src);
free (buffer);
return retVal;
}
// Loads a 16-bit integer from the file at the specified file offset. The saved value is assumed to have been
// processed by mputWord(). The result is stored in *result. Returns TRUE if successful (otherwise FALSE).
BOOL LoadInt16 (const wchar_t *filePath, int *result, __int64 fileOffset)
{
DWORD bufSize = sizeof(__int16);
unsigned char *buffer = (unsigned char *) malloc (bufSize);
unsigned char *bufferPtr = buffer;
HANDLE src = NULL;
DWORD bytesRead;
LARGE_INTEGER seekOffset, seekOffsetNew;
BOOL retVal = FALSE;
if (buffer == NULL)
return -1;
src = CreateFile (filePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (src == INVALID_HANDLE_VALUE)
{
free (buffer);
return FALSE;
}
seekOffset.QuadPart = fileOffset;
if (SetFilePointerEx (src, seekOffset, &seekOffsetNew, FILE_BEGIN) == 0)
goto fsif_end;
if (ReadFile (src, buffer, bufSize, &bytesRead, NULL) == 0
|| bytesRead != bufSize)
goto fsif_end;
retVal = TRUE;
*result = mgetWord(bufferPtr);
fsif_end:
CloseHandle (src);
free (buffer);
return retVal;
}
// Returns NULL if there's any error. Although the buffer can contain binary data, it is always null-terminated.
char *LoadFile (const wchar_t *fileName, DWORD *size)
{
char *buf;
DWORD fileSize = INVALID_FILE_SIZE;
HANDLE h = CreateFile (fileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
*size = 0;
if (h == INVALID_HANDLE_VALUE)
return NULL;
if ((fileSize = GetFileSize (h, NULL)) == INVALID_FILE_SIZE)
{
CloseHandle (h);
return NULL;
}
buf = (char *) calloc (fileSize + 1, 1);
if (buf == NULL)
{
CloseHandle (h);
return NULL;
}
if (!ReadFile (h, buf, fileSize, size, NULL))
{
free (buf);
buf = NULL;
}
else
{
buf[*size] = 0; //make coverity happy eventhough buf is guaranteed to be null terminated because of fileSize+1 in calloc call
}
CloseHandle (h);
return buf;
}
// Returns NULL if there's any error.
char *LoadFileBlock (const wchar_t *fileName, __int64 fileOffset, DWORD count)
{
char *buf;
DWORD bytesRead = 0;
LARGE_INTEGER seekOffset, seekOffsetNew;
BOOL bStatus;
HANDLE h = CreateFile (fileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (h == INVALID_HANDLE_VALUE)
return NULL;
seekOffset.QuadPart = fileOffset;
if (SetFilePointerEx (h, seekOffset, &seekOffsetNew, FILE_BEGIN) == 0)
{
CloseHandle (h);
return NULL;
}
buf = (char *) calloc (count, 1);
if (buf == NULL)
{
CloseHandle (h);
return NULL;
}
bStatus = ReadFile (h, buf, count, &bytesRead, NULL);
CloseHandle (h);
if (!bStatus || (bytesRead != count))
{
free (buf);
return NULL;
}
return buf;
}
// Returns -1 if there is an error, or the size of the file.
__int64 GetFileSize64 (const wchar_t *path)
{
HANDLE h = CreateFile (path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
LARGE_INTEGER size;
__int64 retSize = -1;
if (h)
{
if (GetFileSizeEx (h, &size))
{
retSize = size.QuadPart;
}
CloseHandle (h);
}
return retSize;
}
// If bAppend is TRUE, the buffer is appended to an existing file. If bAppend is FALSE, any existing file
// is replaced. If an error occurs, the incomplete file is deleted (provided that bAppend is FALSE).
BOOL SaveBufferToFile (const char *inputBuffer, const wchar_t *destinationFile, DWORD inputLength, BOOL bAppend, BOOL bRenameIfFailed)
{
HANDLE dst;
DWORD bytesWritten;
BOOL res = TRUE;
DWORD dwLastError = 0;
#if defined(SETUP) && !defined (PORTABLE)
BOOL securityModified = FALSE;
SECURITY_INFO_BACKUP secBackup = { 0 };
const wchar_t* existingFile = destinationFile;
#endif
dst = CreateFile (destinationFile,
GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, bAppend ? OPEN_EXISTING : CREATE_ALWAYS, 0, NULL);
dwLastError = GetLastError();
if (!bAppend && bRenameIfFailed && (dst == INVALID_HANDLE_VALUE) && (GetLastError () == ERROR_SHARING_VIOLATION || GetLastError() == ERROR_ACCESS_DENIED))
{
wchar_t renamedPath[TC_MAX_PATH + 1];
StringCbCopyW (renamedPath, sizeof(renamedPath), destinationFile);
StringCbCatW (renamedPath, sizeof(renamedPath), VC_FILENAME_RENAMED_SUFFIX);
#if defined(SETUP) && !defined (PORTABLE)
// Take ownership of the file
securityModified = ModifyFileSecurityPermissions(destinationFile, &secBackup);
#endif
/* rename the locked file in order to be able to create a new one */
if (MoveFileEx (destinationFile, renamedPath, MOVEFILE_REPLACE_EXISTING))
{
dst = CreateFile (destinationFile,
GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, NULL);
dwLastError = GetLastError();
if (dst == INVALID_HANDLE_VALUE)
{
/* restore the original file name */
MoveFileEx (renamedPath, destinationFile, MOVEFILE_REPLACE_EXISTING);
}
else
{
#if defined(SETUP) && !defined (PORTABLE)
existingFile = renamedPath;
#endif
/* delete the renamed file when the machine reboots */
MoveFileEx (renamedPath, NULL, MOVEFILE_DELAY_UNTIL_REBOOT);
}
}
#if defined(SETUP) && !defined (PORTABLE)
if (securityModified)
{
RestoreSecurityInfo(existingFile, &secBackup);
FreeSecurityBackup(&secBackup);
}
#endif
}
if (dst == INVALID_HANDLE_VALUE)
{
SetLastError (dwLastError);
handleWin32Error (MainDlg, SRC_POS);
return FALSE;
}
if (bAppend)
SetFilePointer (dst, 0, NULL, FILE_END);
if (!WriteFile (dst, inputBuffer, inputLength, &bytesWritten, NULL)
|| inputLength != bytesWritten)
{
res = FALSE;
}
if (!res)
{
// If CREATE_ALWAYS is used, ERROR_ALREADY_EXISTS is returned after successful overwrite
// of an existing file (it's not an error)
if (! (GetLastError() == ERROR_ALREADY_EXISTS && !bAppend) )
handleWin32Error (MainDlg, SRC_POS);
}
CloseHandle (dst);
if (!res && !bAppend)
_wremove (destinationFile);
return res;
}
// Returns -1 if the specified string is not found in the buffer. Otherwise, returns the
// offset of the first occurrence of the string. The string and the buffer may contain zeroes,
// which do NOT terminate them.
int64 FindString (const char *buf, const char *str, int64 bufLen, int64 strLen, int64 startOffset)
{
if (buf == NULL
|| str == NULL
|| strLen > bufLen
|| bufLen < 1
|| strLen < 1
|| startOffset > bufLen - strLen)
{
return -1;
}
for (int64 i = startOffset; i <= bufLen - strLen; i++)
{
if (memcmp (buf + i, str, (size_t) strLen) == 0)
return i;
}
return -1;
}
// Returns TRUE if the file or directory exists (both may be enclosed in quotation marks).
BOOL FileExists (const wchar_t *filePathPtr)
{
wchar_t filePath [TC_MAX_PATH * 2 + 1];
// Strip quotation marks (if any)
if (filePathPtr [0] == L'"')
{
StringCbCopyW (filePath, sizeof(filePath), filePathPtr + 1);
}
else
{
StringCbCopyW (filePath, sizeof(filePath), filePathPtr);
}
// Strip quotation marks (if any)
if (filePath [wcslen (filePath) - 1] == L'"')
filePath [wcslen (filePath) - 1] = 0;
return (_waccess (filePath, 0) != -1);
}
// Searches the file from its end for the LAST occurrence of the string str.
// The string may contain zeroes, which do NOT terminate the string.
// If the string is found, its offset from the start of the file is returned.
// If the string isn't found or if any error occurs, -1 is returned.
__int64 FindStringInFile (const wchar_t *filePath, const char* str, int strLen)
{
int bufSize = 64 * BYTES_PER_KB;
char *buffer = (char *) err_malloc (bufSize);
HANDLE src = NULL;
DWORD bytesRead;
BOOL readRetVal;
__int64 filePos = GetFileSize64 (filePath);
int bufPos = 0;
LARGE_INTEGER seekOffset, seekOffsetNew;
BOOL bExit = FALSE;
int filePosStep;
__int64 retVal = -1;
if (filePos <= 0
|| buffer == NULL
|| strLen > bufSize
|| strLen < 1)
{
if (buffer)
free (buffer);
return -1;
}
src = CreateFile (filePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (src == INVALID_HANDLE_VALUE)
{
free (buffer);
return -1;
}
filePosStep = bufSize - strLen + 1;
do
{
filePos -= filePosStep;
if (filePos < 0)
{
filePos = 0;
bExit = TRUE;
}
seekOffset.QuadPart = filePos;
if (SetFilePointerEx (src, seekOffset, &seekOffsetNew, FILE_BEGIN) == 0)
goto fsif_end;
if ((readRetVal = ReadFile (src, buffer, bufSize, &bytesRead, NULL)) == 0
|| bytesRead == 0)
goto fsif_end;
bufPos = bytesRead - strLen;
while (bufPos > 0)
{
if (memcmp (buffer + bufPos, str, strLen) == 0)
{
// String found
retVal = filePos + bufPos;
goto fsif_end;
}
bufPos--;
}
} while (!bExit);
fsif_end:
CloseHandle (src);
free (buffer);
return retVal;
}
// System CopyFile() copies source file attributes (like FILE_ATTRIBUTE_ENCRYPTED)
// so we need to use our own copy function
BOOL TCCopyFileBase (HANDLE src, HANDLE dst)
{
__int8 *buffer;
FILETIME fileTime;
DWORD bytesRead, bytesWritten;
BOOL res;
buffer = (char *) malloc (64 * 1024);
if (!buffer)
{
CloseHandle (src);
CloseHandle (dst);
return FALSE;
}
while (res = ReadFile (src, buffer, 64 * 1024, &bytesRead, NULL))
{
if (bytesRead == 0)
{
res = 1;
break;
}
if (!WriteFile (dst, buffer, bytesRead, &bytesWritten, NULL)
|| bytesRead != bytesWritten)
{
res = 0;
break;
}
}
if (GetFileTime (src, NULL, NULL, &fileTime))
SetFileTime (dst, NULL, NULL, &fileTime);
CloseHandle (src);
CloseHandle (dst);
free (buffer);
return res != 0;
}
BOOL TCCopyFile (wchar_t *sourceFileName, wchar_t *destinationFile)
{
HANDLE src, dst;
src = CreateFileW (sourceFileName,
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (src == INVALID_HANDLE_VALUE)
return FALSE;
dst = CreateFileW (destinationFile,
GENERIC_WRITE,
0, NULL, CREATE_ALWAYS, 0, NULL);
if (dst == INVALID_HANDLE_VALUE)
{
CloseHandle (src);
return FALSE;
}
return TCCopyFileBase (src, dst);
}
#if !defined(_WIN64) && defined(NDEBUG) && !defined (VC_SKIP_OS_DRIVER_REQ_CHECK)
// in 32-bit build, Crypto project is not compiled so we need to provide this function here
#pragma comment(lib, "bcrypt.lib")
void sha512(unsigned char* result, const unsigned char* source, uint64_t sourceLen)
{
BCRYPT_ALG_HANDLE hAlg = NULL;
BCRYPT_HASH_HANDLE hHash = NULL;
NTSTATUS status = 0;
// Open an algorithm provider for SHA512.
status = BCryptOpenAlgorithmProvider(
&hAlg,
BCRYPT_SHA512_ALGORITHM,
NULL,
0);
if (!BCRYPT_SUCCESS(status))
{
goto cleanup;
}
// Create a hash handle.
status = BCryptCreateHash(
hAlg,
&hHash,
NULL,
0,
NULL, // Optional secret, not needed for SHA512
0,
0);
if (!BCRYPT_SUCCESS(status))
{
goto cleanup;
}
// Hash the data. Note: BCryptHashData takes an ULONG for the length.
status = BCryptHashData(
hHash,
(PUCHAR)source,
(ULONG)sourceLen,
0);
if (!BCRYPT_SUCCESS(status))
{
goto cleanup;
}
// Finalize the hash computation and write the result.
status = BCryptFinishHash(
hHash,
result,
SHA512_DIGESTSIZE,
0);
if (!BCRYPT_SUCCESS(status))
{
goto cleanup;
}
cleanup:
if (hHash)
{
BCryptDestroyHash(hHash);
}
if (hAlg)
{
BCryptCloseAlgorithmProvider(hAlg, 0);
}
}
#endif
BOOL VerifyModuleSignature (const wchar_t* path)
{
#if defined(NDEBUG) && !defined (VC_SKIP_OS_DRIVER_REQ_CHECK)
BOOL bResult = FALSE;
HRESULT hResult;
GUID gActionID = WINTRUST_ACTION_GENERIC_VERIFY_V2;
WINTRUST_FILE_INFO fileInfo = {0};
WINTRUST_DATA WVTData = {0};
wchar_t filePath [TC_MAX_PATH + 1024];
// Strip quotation marks (if any)
if (path [0] == L'"')
{
StringCbCopyW (filePath, sizeof(filePath), path + 1);
}
else
{
StringCbCopyW (filePath, sizeof(filePath), path);
}
// Strip quotation marks (if any)
if (filePath [wcslen (filePath) - 1] == L'"')
filePath [wcslen (filePath) - 1] = 0;
fileInfo.cbStruct = sizeof(WINTRUST_FILE_INFO);
fileInfo.pcwszFilePath = filePath;
fileInfo.hFile = NULL;
WVTData.cbStruct = sizeof(WINTRUST_DATA);
WVTData.dwUIChoice = WTD_UI_NONE;
WVTData.fdwRevocationChecks = WTD_REVOKE_NONE;
WVTData.dwUnionChoice = WTD_CHOICE_FILE;
WVTData.pFile = &fileInfo;
WVTData.dwStateAction = WTD_STATEACTION_VERIFY;
WVTData.dwProvFlags = WTD_REVOCATION_CHECK_NONE | WTD_CACHE_ONLY_URL_RETRIEVAL;
hResult = WinVerifyTrust(0, &gActionID, &WVTData);
if (0 == hResult)
{
PCRYPT_PROVIDER_DATA pProviderData = WTHelperProvDataFromStateData (WVTData.hWVTStateData);
if (pProviderData)
{
PCRYPT_PROVIDER_SGNR pProviderSigner = WTHelperGetProvSignerFromChain (pProviderData, 0, FALSE, 0);
if (pProviderSigner)
{
PCRYPT_PROVIDER_CERT pProviderCert = WTHelperGetProvCertFromChain (pProviderSigner, 0);
if (pProviderCert && (pProviderCert->pCert))
{
BYTE hashVal[64];
sha512 (hashVal, pProviderCert->pCert->pbCertEncoded, pProviderCert->pCert->cbCertEncoded);
if ( (0 == memcmp (hashVal, gpbSha512CodeSignCertFingerprint, 64))
|| (0 == memcmp (hashVal, gpbSha512MSCodeSignCertFingerprint, 64))
)