"Fossies" - the Fresh Open Source Software Archive

Member "src/Common/BootEncryption.h" (10 Oct 2018, 12721 Bytes) of package /windows/misc/VeraCrypt_1.23-Hotfix-2_Source.zip:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "BootEncryption.h" see the Fossies "Dox" file reference documentation and the last Fossies "Diffs" side-by-side code changes report: 1.22_Source_vs_1.23_Source.

    1 /*
    2  Derived from source code of TrueCrypt 7.1a, which is
    3  Copyright (c) 2008-2012 TrueCrypt Developers Association and which is governed
    4  by the TrueCrypt License 3.0.
    5 
    6  Modifications and additions to the original source code (contained in this file) 
    7  and all other portions of this file are Copyright (c) 2013-2017 IDRIX
    8  and are governed by the Apache License 2.0 the full text of which is
    9  contained in the file License.txt included in VeraCrypt binary and source
   10  code distribution packages.
   11 */
   12 
   13 #ifndef TC_HEADER_Common_BootEncryption
   14 #define TC_HEADER_Common_BootEncryption
   15 
   16 #include "Tcdefs.h"
   17 #include "Dlgcode.h"
   18 #include "Exception.h"
   19 #include "Platform/PlatformBase.h"
   20 #include "Volumes.h"
   21 #include <Winternl.h>
   22 
   23 #define SYSPARTITIONINFORMATION 0x62
   24 
   25 typedef NTSTATUS (WINAPI *NtQuerySystemInformationFn)(
   26         SYSTEM_INFORMATION_CLASS SystemInformationClass,
   27         PVOID                    SystemInformation,
   28       ULONG                    SystemInformationLength,
   29         PULONG                   ReturnLength
   30 );
   31 
   32 using namespace std;
   33 
   34 namespace VeraCrypt
   35 {
   36     class File
   37     {
   38     public:
   39         File () : Elevated (false), FileOpen (false), ReadOnly (false), FilePointerPosition(0), Handle(INVALID_HANDLE_VALUE), IsDevice(false), LastError(0) { }
   40         File (wstring path,bool readOnly = false, bool create = false);
   41         virtual ~File () { Close(); }
   42 
   43         bool IsOpened () const { return FileOpen;}
   44         void CheckOpened (const char* srcPos) { if (!FileOpen) { SetLastError (LastError); throw SystemException (srcPos);} }
   45         void Close ();
   46         DWORD Read (byte *buffer, DWORD size);
   47         void Write (byte *buffer, DWORD size);
   48         void SeekAt (int64 position);
   49         void GetFileSize (unsigned __int64& size);
   50         void GetFileSize (DWORD& dwSize);
   51       bool IoCtl(DWORD code, void* inBuf, DWORD inBufSize, void* outBuf, DWORD outBufSize);
   52 
   53     protected:
   54         bool Elevated;
   55         bool FileOpen;
   56         bool ReadOnly;
   57         uint64 FilePointerPosition;
   58         HANDLE Handle;
   59         bool IsDevice;
   60         wstring Path;
   61         DWORD LastError;
   62         BYTE ReadBuffer[4096];
   63     };
   64 
   65 
   66     class Device : public File
   67     {
   68     public:
   69         Device (wstring path,bool readOnly = false);
   70         virtual ~Device () {}
   71     };
   72 
   73 
   74     class Buffer
   75     {
   76     public:
   77         Buffer (size_t size) : DataSize (size)
   78         {
   79             DataPtr = new byte[size];
   80             if (!DataPtr)
   81                 throw bad_alloc();
   82         }
   83 
   84         ~Buffer () { delete[] DataPtr; }
   85         byte *Ptr () const { return DataPtr; }
   86         size_t Size () const { return DataSize; }
   87         void Resize (size_t newSize)
   88         { 
   89             if (newSize > DataSize)
   90             {
   91                 byte *tmp = new byte[newSize];
   92                 if (!tmp)
   93                     throw bad_alloc();
   94                 memcpy (tmp, DataPtr, DataSize);
   95                 delete [] DataPtr;          
   96                 DataPtr = tmp;
   97             }
   98             DataSize = newSize;
   99         }
  100 
  101     protected:
  102         byte *DataPtr;
  103         size_t DataSize;
  104     };
  105 
  106 
  107     struct Partition
  108     {
  109         wstring DevicePath;
  110         PARTITION_INFORMATION Info;
  111         wstring MountPoint;
  112         size_t Number;
  113         BOOL IsGPT;
  114         wstring VolumeNameId;
  115     };
  116 
  117     typedef list <Partition> PartitionList;
  118 
  119 #pragma pack (push)
  120 #pragma pack(1)
  121 
  122     struct PartitionEntryMBR
  123     {
  124         byte BootIndicator;
  125 
  126         byte StartHead;
  127         byte StartCylSector;
  128         byte StartCylinder;
  129 
  130         byte Type;
  131 
  132         byte EndHead;
  133         byte EndSector;
  134         byte EndCylinder;
  135 
  136         uint32 StartLBA;
  137         uint32 SectorCountLBA;
  138     };
  139 
  140     struct MBR
  141     {
  142         byte Code[446];
  143         PartitionEntryMBR Partitions[4];
  144         uint16 Signature;
  145     };
  146 
  147 #pragma pack (pop)
  148 
  149     struct SystemDriveConfiguration
  150     {
  151         wstring DeviceKernelPath;
  152         wstring DevicePath;
  153         int DriveNumber;
  154         Partition DrivePartition;
  155         bool ExtraBootPartitionPresent;
  156         int64 InitialUnallocatedSpace;
  157         PartitionList Partitions;
  158         Partition SystemPartition;
  159         int64 TotalUnallocatedSpace;
  160         bool SystemLoaderPresent;
  161     };
  162 
  163     class EfiBootConf
  164     {
  165     public:
  166 
  167         int passwordType;
  168         string passwordMsg;
  169         string passwordPicture;
  170         string hashMsg;
  171         int hashAlgo;
  172         int requestHash;
  173         string pimMsg;
  174         int pim;
  175         int requestPim;
  176         int authorizeVisible;
  177         int authorizeRetry;
  178         int bmlLockFlags;
  179         int bmlDriverEnabled;
  180         string actionSuccessValue;
  181 
  182         EfiBootConf();
  183 
  184         static BOOL ReadConfigValue (char* configContent, const char *configKey, char *configValue, int maxValueSize);
  185         static int ReadConfigInteger (char* configContent, const char *configKey, int defaultValue);
  186         static char *ReadConfigString (char* configContent, const char *configKey, char *defaultValue, char *str, int maxLen);
  187         static BOOL WriteConfigString (FILE* configFile, char* configContent, const char *configKey, const char *configValue);
  188         static BOOL WriteConfigInteger (FILE* configFile, char* configContent, const char *configKey, int configValue);
  189         BOOL Load (const wchar_t* fileName);
  190         void Load (char* configContent);
  191         BOOL Save (const wchar_t* fileName, HWND hwnd);
  192     };
  193 
  194     void GetVolumeESP(wstring& path);
  195     std::string ReadESPFile (LPCWSTR szFilePath, bool bSkipUTF8BOM);
  196     void WriteESPFile (LPCWSTR szFilePath, LPBYTE pbData, DWORD dwDataLen, bool bAddUTF8BOM);
  197 
  198     class EfiBoot {
  199     public:
  200         EfiBoot();
  201 
  202         void MountBootPartition(WCHAR letter);
  203         void DismountBootPartition();
  204         bool IsEfiBoot();
  205 
  206         void DeleteStartExec(uint16 statrtOrderNum = 0xDC5B, wchar_t* type = NULL);
  207         void SetStartExec(wstring description, wstring execPath, uint16 statrtOrderNum = 0xDC5B, wchar_t* type = NULL, uint32 attr = 1);
  208         void SaveFile(const wchar_t* name, byte* data, DWORD size);
  209         void GetFileSize(const wchar_t* name, unsigned __int64& size);
  210         void ReadFile(const wchar_t* name, byte* data, DWORD size);
  211         void CopyFile(const wchar_t* name, const wchar_t* targetName);
  212         bool FileExists(const wchar_t* name);
  213 
  214         BOOL RenameFile(const wchar_t* name, wchar_t* nameNew, BOOL bForce);
  215         BOOL DelFile(const wchar_t* name);
  216         BOOL MkDir(const wchar_t* name, bool& bAlreadyExists);
  217         BOOL ReadConfig (const wchar_t* name, EfiBootConf& conf);
  218         BOOL UpdateConfig (const wchar_t* name, int pim, int hashAlgo, HWND hwndDlg);
  219         BOOL WriteConfig (const wchar_t* name, bool preserveUserConfig, int pim, int hashAlgo, const char* passPromptMsg, HWND hwndDlg);
  220         BOOL DelDir(const wchar_t* name);
  221         void SelectBootVolumeESP();
  222         void SelectBootVolume(WCHAR* bootVolumePath);
  223         PSTORAGE_DEVICE_NUMBER GetStorageDeviceNumber () { return &sdn;}
  224 
  225     protected:
  226         bool m_bMounted;
  227         WCHAR   EfiBootPartPath[3];
  228         STORAGE_DEVICE_NUMBER sdn;
  229         PARTITION_INFORMATION_EX partInfo;
  230         WCHAR     tempBuf[1024];
  231         bool  bBootVolumePathSelected;
  232         WCHAR BootVolumePath[MAX_PATH];
  233     };
  234 
  235     class BootEncryption
  236     {
  237     public:
  238         BootEncryption (HWND parent, bool postOOBE = false);
  239         ~BootEncryption ();
  240 
  241         enum FilterType
  242         {
  243             DriveFilter,
  244             VolumeFilter,
  245             DumpFilter
  246         };
  247 
  248         void SetParentWindow (HWND parent) { ParentWindow = parent; }
  249         void AbortDecoyOSWipe ();
  250         void AbortSetup ();
  251         void AbortSetupWait ();
  252         void CallDriver (DWORD ioctl, void *input = nullptr, DWORD inputSize = 0, void *output = nullptr, DWORD outputSize = 0);
  253         int ChangePassword (Password *oldPassword, int old_pkcs5, int old_pim, Password *newPassword, int pkcs5, int pim, int wipePassCount, HWND hwndDlg);
  254         void CheckDecoyOSWipeResult ();
  255         void CheckEncryptionSetupResult ();
  256         void CheckRequirements ();
  257         void CheckRequirementsHiddenOS ();
  258         void CopyFileAdmin (const wstring &sourceFile, const wstring &destinationFile);
  259         void CreateRescueIsoImage (bool initialSetup, const wstring &isoImagePath);
  260         void Deinstall (bool displayWaitDialog = false);
  261         void DeleteFileAdmin (const wstring &file);
  262         DecoySystemWipeStatus GetDecoyOSWipeStatus ();
  263         DWORD GetDriverServiceStartType ();
  264         unsigned int GetHiddenOSCreationPhase ();
  265         uint16 GetInstalledBootLoaderVersion ();
  266         void GetInstalledBootLoaderFingerprint (byte fingerprint[WHIRLPOOL_DIGESTSIZE + SHA512_DIGESTSIZE]);
  267         Partition GetPartitionForHiddenOS ();
  268         bool IsBootLoaderOnDrive (wchar_t *devicePath);
  269         BootEncryptionStatus GetStatus ();
  270         void GetVolumeProperties (VOLUME_PROPERTIES_STRUCT *properties);
  271         SystemDriveConfiguration GetSystemDriveConfiguration ();
  272         void Install (bool hiddenSystem, int hashAlgo);
  273         void InstallBootLoader (Device& device, bool preserveUserConfig = false, bool hiddenOSCreation = false, int pim = -1, int hashAlg = -1);
  274         void InstallBootLoader (bool preserveUserConfig = false, bool hiddenOSCreation = false, int pim = -1, int hashAlg = -1);
  275         bool CheckBootloaderFingerprint (bool bSilent = false);
  276         void InvalidateCachedSysDriveProperties ();
  277         bool IsCDRecorderPresent ();
  278         bool IsHiddenSystemRunning ();
  279         bool IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly);
  280         void PrepareHiddenOSCreation (int ea, int mode, int pkcs5);
  281         void PrepareInstallation (bool systemPartitionOnly, Password &password, int ea, int mode, int pkcs5, int pim, const wstring &rescueIsoImagePath);
  282         void ProbeRealSystemDriveSize ();
  283         bool ReadBootSectorConfig (byte *config, size_t bufLength, byte *userConfig = nullptr, string *customUserMessage = nullptr, uint16 *bootLoaderVersion = nullptr);
  284         uint32 ReadDriverConfigurationFlags ();
  285         void RegisterBootDriver (bool hiddenSystem);
  286         void RegisterFilterDriver (bool registerDriver, FilterType filterType);
  287         void RegisterSystemFavoritesService (BOOL registerService);
  288         void RegisterSystemFavoritesService (BOOL registerService, BOOL noFileHandling);
  289         void UpdateSystemFavoritesService ();
  290         void RenameDeprecatedSystemLoaderBackup ();
  291         bool RestartComputer (BOOL bShutdown = FALSE);
  292         void InitialSecurityChecksForHiddenOS ();
  293         void RestrictPagingFilesToSystemPartition ();
  294         void SetDriverConfigurationFlag (uint32 flag, bool state);
  295         void SetDriverServiceStartType (DWORD startType);
  296         void SetHiddenOSCreationPhase (unsigned int newPhase);
  297         void StartDecryption (BOOL discardUnreadableEncryptedSectors);
  298         void StartDecoyOSWipe (WipeAlgorithmId wipeAlgorithm);
  299         void StartEncryption (WipeAlgorithmId wipeAlgorithm, bool zeroUnreadableSectors);
  300         bool SystemDriveContainsPartitionType (byte type);
  301         bool SystemDriveContainsExtendedPartition ();
  302         bool SystemDriveContainsNonStandardPartitions ();
  303         bool SystemPartitionCoversWholeDrive ();
  304         bool SystemDriveIsDynamic ();
  305         bool VerifyRescueDisk ();
  306         bool VerifyRescueDiskImage (const wchar_t* imageFile);
  307         void WipeHiddenOSCreationConfig ();
  308         void WriteBootDriveSector (uint64 offset, byte *data);
  309         void WriteBootSectorConfig (const byte newConfig[]);
  310         void WriteBootSectorUserConfig (byte userConfig, const string &customUserMessage, int pim, int hashAlg);
  311         void WriteEfiBootSectorUserConfig (byte userConfig, const string &customUserMessage, int pim, int hashAlg);
  312         void WriteLocalMachineRegistryDwordValue (wchar_t *keyPath, wchar_t *valueName, DWORD value);
  313         void GetEfiBootDeviceNumber (PSTORAGE_DEVICE_NUMBER pSdn);
  314         void BackupSystemLoader ();
  315         void RestoreSystemLoader ();
  316         static void UpdateSetupConfigFile (bool bForInstall);
  317         void GetSecureBootConfig (BOOL* pSecureBootEnabled, BOOL *pVeraCryptKeysLoaded);
  318     protected:
  319         static const uint32 RescueIsoImageSize = 1835008; // Size of ISO9660 image with bootable emulated 1.44MB floppy disk image
  320 
  321         void CreateBootLoaderInMemory (byte *buffer, size_t bufferSize, bool rescueDisk, bool hiddenOSCreation = false);
  322         void CreateVolumeHeader (uint64 volumeSize, uint64 encryptedAreaStart, Password *password, int ea, int mode, int pkcs5, int pim);
  323         wstring GetSystemLoaderBackupPath ();
  324         uint32 GetChecksum (byte *data, size_t size);
  325         DISK_GEOMETRY_EX GetDriveGeometry (int driveNumber);
  326         PartitionList GetDrivePartitions (int driveNumber);
  327         wstring GetRemarksOnHiddenOS ();
  328         wstring GetWindowsDirectory ();
  329         void RegisterFilter (bool registerFilter, FilterType filterType, const GUID *deviceClassGuid = nullptr);        
  330         void InstallVolumeHeader ();
  331 
  332         HWND ParentWindow;
  333         SystemDriveConfiguration DriveConfig;
  334         int SelectedEncryptionAlgorithmId;
  335         int SelectedPrfAlgorithmId;
  336         Partition HiddenOSCandidatePartition;
  337         byte *RescueIsoImage;
  338         byte *RescueZipData;
  339         unsigned long RescueZipSize;
  340         byte RescueVolumeHeader[TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE];
  341         byte VolumeHeader[TC_BOOT_ENCRYPTION_VOLUME_HEADER_SIZE];
  342         bool DriveConfigValid;
  343         bool RealSystemDriveSizeValid;
  344         bool RescueVolumeHeaderValid;
  345         bool VolumeHeaderValid;
  346         bool PostOOBEMode;
  347     };
  348 }
  349 
  350 #define TC_ABORT_TRANSFORM_WAIT_INTERVAL    10
  351 
  352 #define MIN_HIDDENOS_DECOY_PARTITION_SIZE_RATIO_NTFS    2.1
  353 #define MIN_HIDDENOS_DECOY_PARTITION_SIZE_RATIO_FAT     1.05
  354 
  355 #define TC_SYS_BOOT_LOADER_BACKUP_NAME          L"Original System Loader"
  356 #define TC_SYS_BOOT_LOADER_BACKUP_NAME_LEGACY   L"Original System Loader.bak"   // Deprecated to prevent removal by some "cleaners"
  357 
  358 #define TC_SYSTEM_FAVORITES_SERVICE_NAME                _T(TC_APP_NAME) L"SystemFavorites"
  359 #define TC_SYSTEM_FAVORITES_SERVICE_LOAD_ORDER_GROUP    L"Event Log"
  360 #define TC_SYSTEM_FAVORITES_SERVICE_CMDLINE_OPTION      L"/systemFavoritesService"
  361 
  362 #define VC_WINDOWS_UPGRADE_POSTOOBE_CMDLINE_OPTION      L"/PostOOBE"
  363 
  364 #endif // TC_HEADER_Common_BootEncryption