PageRenderTime 27ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/Format/InPlace.c

https://github.com/pcmac77/truecrypt-android
C | 1692 lines | 1181 code | 413 blank | 98 comment | 288 complexity | def4d9a63e557881e10db7d010674ff1 MD5 | raw file
  1. /*
  2. Copyright (c) 2008-2010 TrueCrypt Developers Association. All rights reserved.
  3. Governed by the TrueCrypt License 3.0 the full text of which is contained in
  4. the file License.txt included in TrueCrypt binary and source code distribution
  5. packages.
  6. */
  7. /* In this file, _WIN32_WINNT is defined as 0x0600 to make filesystem shrink available (Vista
  8. or later). _WIN32_WINNT cannot be defined as 0x0600 for the entire user-space projects
  9. because it breaks the main font app when the app is running on XP (likely an MS bug).
  10. IMPORTANT: Due to this issue, functions in this file must not directly interact with GUI. */
  11. #define TC_LOCAL_WIN32_WINNT_OVERRIDE 1
  12. #if (_WIN32_WINNT < 0x0600)
  13. # undef _WIN32_WINNT
  14. # define _WIN32_WINNT 0x0600
  15. #endif
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #include <string>
  19. #include "Tcdefs.h"
  20. #include "Platform/Finally.h"
  21. #include "Common.h"
  22. #include "Crc.h"
  23. #include "Dlgcode.h"
  24. #include "Language.h"
  25. #include "Tcformat.h"
  26. #include "Volumes.h"
  27. #include "InPlace.h"
  28. using namespace std;
  29. using namespace TrueCrypt;
  30. #define TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE (2048 * BYTES_PER_KB)
  31. #define TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE (2 * TC_MAX_VOLUME_SECTOR_SIZE)
  32. #define TC_NTFS_CONCEAL_CONSTANT 0xFF
  33. #define TC_NONSYS_INPLACE_ENC_HEADER_UPDATE_INTERVAL (64 * BYTES_PER_MB)
  34. #define TC_NONSYS_INPLACE_ENC_MIN_VOL_SIZE (TC_TOTAL_VOLUME_HEADERS_SIZE + TC_MIN_NTFS_FS_SIZE * 2)
  35. // If the returned value is greater than 0, it is the desired volume size in NTFS sectors (not in bytes)
  36. // after shrinking has been performed. If there's any error, returns -1.
  37. static __int64 NewFileSysSizeAfterShrink (HANDLE dev, const char *devicePath, int64 *totalClusterCount, DWORD *bytesPerCluster, BOOL silent)
  38. {
  39. NTFS_VOLUME_DATA_BUFFER ntfsVolData;
  40. DWORD nBytesReturned;
  41. __int64 fileSysSize, desiredNbrSectors;
  42. // Filesystem size and sector size
  43. if (!DeviceIoControl (dev,
  44. FSCTL_GET_NTFS_VOLUME_DATA,
  45. NULL,
  46. 0,
  47. (LPVOID) &ntfsVolData,
  48. sizeof (ntfsVolData),
  49. &nBytesReturned,
  50. NULL))
  51. {
  52. if (!silent)
  53. handleWin32Error (MainDlg);
  54. return -1;
  55. }
  56. fileSysSize = ntfsVolData.NumberSectors.QuadPart * ntfsVolData.BytesPerSector;
  57. desiredNbrSectors = (fileSysSize - TC_TOTAL_VOLUME_HEADERS_SIZE) / ntfsVolData.BytesPerSector;
  58. if (desiredNbrSectors <= 0)
  59. return -1;
  60. if (totalClusterCount)
  61. *totalClusterCount = ntfsVolData.TotalClusters.QuadPart;
  62. if (bytesPerCluster)
  63. *bytesPerCluster = ntfsVolData.BytesPerCluster;
  64. return desiredNbrSectors;
  65. }
  66. BOOL CheckRequirementsForNonSysInPlaceEnc (const char *devicePath, BOOL silent)
  67. {
  68. NTFS_VOLUME_DATA_BUFFER ntfsVolData;
  69. DWORD nBytesReturned;
  70. HANDLE dev;
  71. char szFileSysName [256];
  72. WCHAR devPath [MAX_PATH];
  73. char dosDev [TC_MAX_PATH] = {0};
  74. char devName [MAX_PATH] = {0};
  75. int driveLetterNo = -1;
  76. char szRootPath[4] = {0, ':', '\\', 0};
  77. __int64 deviceSize;
  78. int partitionNumber = -1, driveNumber = -1;
  79. /* ---------- Checks that do not require admin rights ----------- */
  80. /* Operating system */
  81. if (CurrentOSMajor < 6)
  82. {
  83. if (!silent)
  84. ShowInPlaceEncErrMsgWAltSteps ("OS_NOT_SUPPORTED_FOR_NONSYS_INPLACE_ENC", FALSE);
  85. return FALSE;
  86. }
  87. /* Volume type (must be a partition or a dynamic volume) */
  88. if (sscanf (devicePath, "\\Device\\HarddiskVolume%d", &partitionNumber) != 1
  89. && sscanf (devicePath, "\\Device\\Harddisk%d\\Partition%d", &driveNumber, &partitionNumber) != 2)
  90. {
  91. if (!silent)
  92. Error ("INPLACE_ENC_INVALID_PATH");
  93. return FALSE;
  94. }
  95. if (partitionNumber == 0)
  96. {
  97. if (!silent)
  98. Warning ("RAW_DEV_NOT_SUPPORTED_FOR_INPLACE_ENC");
  99. return FALSE;
  100. }
  101. /* Admin rights */
  102. if (!IsAdmin())
  103. {
  104. // We rely on the wizard process to call us only when the whole wizard process has been elevated (so UAC
  105. // status can be ignored). In case the IsAdmin() detection somehow fails, we allow the user to continue.
  106. if (!silent)
  107. Warning ("ADMIN_PRIVILEGES_WARN_DEVICES");
  108. }
  109. /* ---------- Checks that may require admin rights ----------- */
  110. /* Access to the partition */
  111. strcpy ((char *) devPath, devicePath);
  112. ToUNICODE ((char *) devPath);
  113. driveLetterNo = GetDiskDeviceDriveLetter (devPath);
  114. if (driveLetterNo >= 0)
  115. szRootPath[0] = (char) driveLetterNo + 'A';
  116. if (FakeDosNameForDevice (devicePath, dosDev, devName, FALSE) != 0)
  117. {
  118. if (!silent)
  119. {
  120. handleWin32Error (MainDlg);
  121. Error ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL");
  122. }
  123. return FALSE;
  124. }
  125. dev = OpenPartitionVolume (devName,
  126. FALSE, // Do not require exclusive access
  127. TRUE, // Require shared access (must be TRUE; otherwise, volume properties will not be possible to obtain)
  128. FALSE, // Do not ask the user to confirm shared access (if exclusive fails)
  129. FALSE, // Do not append alternative instructions how to encrypt the data (to applicable error messages)
  130. silent); // Silent mode
  131. if (dev == INVALID_HANDLE_VALUE)
  132. return FALSE;
  133. /* File system type */
  134. GetVolumeInformation (szRootPath, NULL, 0, NULL, NULL, NULL, szFileSysName, sizeof(szFileSysName));
  135. if (strncmp (szFileSysName, "NTFS", 4))
  136. {
  137. // The previous filesystem type detection method failed (or it's not NTFS) -- try an alternative method
  138. if (!DeviceIoControl (dev,
  139. FSCTL_GET_NTFS_VOLUME_DATA,
  140. NULL,
  141. 0,
  142. (LPVOID) &ntfsVolData,
  143. sizeof (ntfsVolData),
  144. &nBytesReturned,
  145. NULL))
  146. {
  147. if (!silent)
  148. {
  149. // The filesystem is not NTFS or the filesystem type could not be determined (or the NTFS filesystem
  150. // is dismounted).
  151. if (IsDeviceMounted (devName))
  152. ShowInPlaceEncErrMsgWAltSteps ("ONLY_NTFS_SUPPORTED_FOR_NONSYS_INPLACE_ENC", FALSE);
  153. else
  154. Warning ("ONLY_MOUNTED_VOL_SUPPORTED_FOR_NONSYS_INPLACE_ENC");
  155. }
  156. CloseHandle (dev);
  157. return FALSE;
  158. }
  159. }
  160. /* Attempt to determine whether the filesystem can be safely shrunk */
  161. if (NewFileSysSizeAfterShrink (dev, devicePath, NULL, NULL, silent) == -1)
  162. {
  163. // Cannot determine whether shrinking is required
  164. if (!silent)
  165. ShowInPlaceEncErrMsgWAltSteps ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE);
  166. CloseHandle (dev);
  167. return FALSE;
  168. }
  169. /* Partition size */
  170. deviceSize = GetDeviceSize (devicePath);
  171. if (deviceSize < 0)
  172. {
  173. // Cannot determine the size of the partition
  174. if (!silent)
  175. Error ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL");
  176. CloseHandle (dev);
  177. return FALSE;
  178. }
  179. if (deviceSize < TC_NONSYS_INPLACE_ENC_MIN_VOL_SIZE)
  180. {
  181. // The partition is too small
  182. if (!silent)
  183. {
  184. ShowInPlaceEncErrMsgWAltSteps ("PARTITION_TOO_SMALL_FOR_NONSYS_INPLACE_ENC", FALSE);
  185. }
  186. CloseHandle (dev);
  187. return FALSE;
  188. }
  189. /* Free space on the filesystem */
  190. if (!DeviceIoControl (dev,
  191. FSCTL_GET_NTFS_VOLUME_DATA,
  192. NULL,
  193. 0,
  194. (LPVOID) &ntfsVolData,
  195. sizeof (ntfsVolData),
  196. &nBytesReturned,
  197. NULL))
  198. {
  199. if (!silent)
  200. ShowInPlaceEncErrMsgWAltSteps ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL", TRUE);
  201. CloseHandle (dev);
  202. return FALSE;
  203. }
  204. if (ntfsVolData.FreeClusters.QuadPart * ntfsVolData.BytesPerCluster < TC_TOTAL_VOLUME_HEADERS_SIZE)
  205. {
  206. if (!silent)
  207. ShowInPlaceEncErrMsgWAltSteps ("NOT_ENOUGH_FREE_FILESYS_SPACE_FOR_SHRINK", TRUE);
  208. CloseHandle (dev);
  209. return FALSE;
  210. }
  211. /* Filesystem sector size */
  212. if (ntfsVolData.BytesPerSector > TC_MAX_VOLUME_SECTOR_SIZE
  213. || ntfsVolData.BytesPerSector % ENCRYPTION_DATA_UNIT_SIZE != 0)
  214. {
  215. if (!silent)
  216. ShowInPlaceEncErrMsgWAltSteps ("SECTOR_SIZE_UNSUPPORTED", TRUE);
  217. CloseHandle (dev);
  218. return FALSE;
  219. }
  220. CloseHandle (dev);
  221. return TRUE;
  222. }
  223. int EncryptPartitionInPlaceBegin (volatile FORMAT_VOL_PARAMETERS *volParams, volatile HANDLE *outHandle, WipeAlgorithmId wipeAlgorithm)
  224. {
  225. SHRINK_VOLUME_INFORMATION shrinkVolInfo;
  226. signed __int64 sizeToShrinkTo;
  227. int nStatus = ERR_SUCCESS;
  228. PCRYPTO_INFO cryptoInfo = NULL;
  229. PCRYPTO_INFO cryptoInfo2 = NULL;
  230. HANDLE dev = INVALID_HANDLE_VALUE;
  231. DWORD dwError;
  232. char *header;
  233. char dosDev[TC_MAX_PATH] = {0};
  234. char devName[MAX_PATH] = {0};
  235. int driveLetter = -1;
  236. WCHAR deviceName[MAX_PATH];
  237. uint64 dataAreaSize;
  238. __int64 deviceSize;
  239. LARGE_INTEGER offset;
  240. DWORD dwResult;
  241. SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_PREPARING);
  242. if (!CheckRequirementsForNonSysInPlaceEnc (volParams->volumePath, FALSE))
  243. return ERR_DONT_REPORT;
  244. header = (char *) TCalloc (TC_VOLUME_HEADER_EFFECTIVE_SIZE);
  245. if (!header)
  246. return ERR_OUTOFMEMORY;
  247. VirtualLock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
  248. deviceSize = GetDeviceSize (volParams->volumePath);
  249. if (deviceSize < 0)
  250. {
  251. // Cannot determine the size of the partition
  252. nStatus = ERR_PARAMETER_INCORRECT;
  253. goto closing_seq;
  254. }
  255. if (deviceSize < TC_NONSYS_INPLACE_ENC_MIN_VOL_SIZE)
  256. {
  257. ShowInPlaceEncErrMsgWAltSteps ("PARTITION_TOO_SMALL_FOR_NONSYS_INPLACE_ENC", TRUE);
  258. nStatus = ERR_DONT_REPORT;
  259. goto closing_seq;
  260. }
  261. dataAreaSize = GetVolumeDataAreaSize (volParams->hiddenVol, deviceSize);
  262. strcpy ((char *)deviceName, volParams->volumePath);
  263. ToUNICODE ((char *)deviceName);
  264. driveLetter = GetDiskDeviceDriveLetter (deviceName);
  265. if (FakeDosNameForDevice (volParams->volumePath, dosDev, devName, FALSE) != 0)
  266. {
  267. nStatus = ERR_OS_ERROR;
  268. goto closing_seq;
  269. }
  270. if (IsDeviceMounted (devName))
  271. {
  272. dev = OpenPartitionVolume (devName,
  273. FALSE, // Do not require exclusive access (must be FALSE; otherwise, it will not be possible to dismount the volume or obtain its properties and FSCTL_ALLOW_EXTENDED_DASD_IO will fail too)
  274. TRUE, // Require shared access (must be TRUE; otherwise, it will not be possible to dismount the volume or obtain its properties and FSCTL_ALLOW_EXTENDED_DASD_IO will fail too)
  275. FALSE, // Do not ask the user to confirm shared access (if exclusive fails)
  276. FALSE, // Do not append alternative instructions how to encrypt the data (to applicable error messages)
  277. FALSE); // Non-silent mode
  278. if (dev == INVALID_HANDLE_VALUE)
  279. {
  280. nStatus = ERR_DONT_REPORT;
  281. goto closing_seq;
  282. }
  283. }
  284. else
  285. {
  286. // The volume is not mounted so we can't work with the filesystem.
  287. Error ("ONLY_MOUNTED_VOL_SUPPORTED_FOR_NONSYS_INPLACE_ENC");
  288. nStatus = ERR_DONT_REPORT;
  289. goto closing_seq;
  290. }
  291. /* Gain "raw" access to the partition (the NTFS driver guards hidden sectors). */
  292. if (!DeviceIoControl (dev,
  293. FSCTL_ALLOW_EXTENDED_DASD_IO,
  294. NULL,
  295. 0,
  296. NULL,
  297. 0,
  298. &dwResult,
  299. NULL))
  300. {
  301. handleWin32Error (MainDlg);
  302. ShowInPlaceEncErrMsgWAltSteps ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE);
  303. nStatus = ERR_DONT_REPORT;
  304. goto closing_seq;
  305. }
  306. /* Shrink the filesystem */
  307. int64 totalClusterCount;
  308. DWORD bytesPerCluster;
  309. sizeToShrinkTo = NewFileSysSizeAfterShrink (dev, volParams->volumePath, &totalClusterCount, &bytesPerCluster, FALSE);
  310. if (sizeToShrinkTo == -1)
  311. {
  312. ShowInPlaceEncErrMsgWAltSteps ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE);
  313. nStatus = ERR_DONT_REPORT;
  314. goto closing_seq;
  315. }
  316. SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_RESIZING);
  317. memset (&shrinkVolInfo, 0, sizeof (shrinkVolInfo));
  318. shrinkVolInfo.ShrinkRequestType = ShrinkPrepare;
  319. shrinkVolInfo.NewNumberOfSectors = sizeToShrinkTo;
  320. if (!DeviceIoControl (dev,
  321. FSCTL_SHRINK_VOLUME,
  322. (LPVOID) &shrinkVolInfo,
  323. sizeof (shrinkVolInfo),
  324. NULL,
  325. 0,
  326. &dwResult,
  327. NULL))
  328. {
  329. handleWin32Error (MainDlg);
  330. ShowInPlaceEncErrMsgWAltSteps ("CANNOT_RESIZE_FILESYS", TRUE);
  331. nStatus = ERR_DONT_REPORT;
  332. goto closing_seq;
  333. }
  334. BOOL clustersMovedBeforeVolumeEnd = FALSE;
  335. while (true)
  336. {
  337. shrinkVolInfo.ShrinkRequestType = ShrinkCommit;
  338. shrinkVolInfo.NewNumberOfSectors = 0;
  339. if (!DeviceIoControl (dev, FSCTL_SHRINK_VOLUME, &shrinkVolInfo, sizeof (shrinkVolInfo), NULL, 0, &dwResult, NULL))
  340. {
  341. // If there are any occupied clusters beyond the new desired end of the volume, the call fails with
  342. // ERROR_ACCESS_DENIED (STATUS_ALREADY_COMMITTED).
  343. if (GetLastError () == ERROR_ACCESS_DENIED)
  344. {
  345. if (!clustersMovedBeforeVolumeEnd)
  346. {
  347. if (MoveClustersBeforeThreshold (dev, deviceName, totalClusterCount - (bytesPerCluster > TC_TOTAL_VOLUME_HEADERS_SIZE ? 1 : TC_TOTAL_VOLUME_HEADERS_SIZE / bytesPerCluster)))
  348. {
  349. clustersMovedBeforeVolumeEnd = TRUE;
  350. continue;
  351. }
  352. handleWin32Error (MainDlg);
  353. }
  354. }
  355. else
  356. handleWin32Error (MainDlg);
  357. ShowInPlaceEncErrMsgWAltSteps ("CANNOT_RESIZE_FILESYS", TRUE);
  358. nStatus = ERR_DONT_REPORT;
  359. goto closing_seq;
  360. }
  361. break;
  362. }
  363. SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_PREPARING);
  364. /* Gain exclusive access to the volume */
  365. nStatus = DismountFileSystem (dev,
  366. driveLetter,
  367. TRUE,
  368. TRUE,
  369. FALSE);
  370. if (nStatus != ERR_SUCCESS)
  371. {
  372. nStatus = ERR_DONT_REPORT;
  373. goto closing_seq;
  374. }
  375. /* Create header backup on the partition. Until the volume is fully encrypted, the backup header will provide
  376. us with the master key, encrypted range, and other data for pause/resume operations. We cannot create the
  377. primary header until the entire partition is encrypted (because we encrypt backwards and the primary header
  378. area is occuppied by data until the very end of the process). */
  379. // Prepare the backup header
  380. for (int wipePass = 0; wipePass < (wipeAlgorithm == TC_WIPE_NONE ? 1 : PRAND_DISK_WIPE_PASSES); wipePass++)
  381. {
  382. nStatus = CreateVolumeHeaderInMemory (FALSE,
  383. header,
  384. volParams->ea,
  385. FIRST_MODE_OF_OPERATION_ID,
  386. volParams->password,
  387. volParams->pkcs5,
  388. wipePass == 0 ? NULL : (char *) cryptoInfo->master_keydata,
  389. &cryptoInfo,
  390. dataAreaSize,
  391. 0,
  392. TC_VOLUME_DATA_OFFSET + dataAreaSize, // Start of the encrypted area = the first byte of the backup heeader (encrypting from the end)
  393. 0, // No data is encrypted yet
  394. 0,
  395. volParams->headerFlags | TC_HEADER_FLAG_NONSYS_INPLACE_ENC,
  396. volParams->sectorSize,
  397. wipeAlgorithm == TC_WIPE_NONE ? FALSE : (wipePass < PRAND_DISK_WIPE_PASSES - 1));
  398. if (nStatus != 0)
  399. goto closing_seq;
  400. offset.QuadPart = TC_VOLUME_DATA_OFFSET + dataAreaSize;
  401. if (!SetFilePointerEx (dev, offset, NULL, FILE_BEGIN))
  402. {
  403. nStatus = ERR_OS_ERROR;
  404. goto closing_seq;
  405. }
  406. // Write the backup header to the partition
  407. if (!WriteEffectiveVolumeHeader (TRUE, dev, (byte *) header))
  408. {
  409. nStatus = ERR_OS_ERROR;
  410. goto closing_seq;
  411. }
  412. // Fill the reserved sectors of the backup header area with random data
  413. nStatus = WriteRandomDataToReservedHeaderAreas (dev, cryptoInfo, dataAreaSize, FALSE, TRUE);
  414. if (nStatus != ERR_SUCCESS)
  415. goto closing_seq;
  416. }
  417. /* Now we will try to decrypt the backup header to verify it has been correctly written. */
  418. nStatus = OpenBackupHeader (dev, volParams->volumePath, volParams->password, &cryptoInfo2, NULL, deviceSize);
  419. if (nStatus != ERR_SUCCESS
  420. || cryptoInfo->EncryptedAreaStart.Value != cryptoInfo2->EncryptedAreaStart.Value
  421. || cryptoInfo2->EncryptedAreaStart.Value == 0)
  422. {
  423. if (nStatus == ERR_SUCCESS)
  424. nStatus = ERR_PARAMETER_INCORRECT;
  425. goto closing_seq;
  426. }
  427. // The backup header is valid so we know we should be able to safely resume in-place encryption
  428. // of this partition even if the system/app crashes.
  429. /* Conceal the NTFS filesystem (by performing an easy-to-undo modification). This will prevent Windows
  430. and apps from interfering with the volume until it has been fully encrypted. */
  431. nStatus = ConcealNTFS (dev);
  432. if (nStatus != ERR_SUCCESS)
  433. goto closing_seq;
  434. // /* If a drive letter is assigned to the device, remove it (so that users do not try to open it, which
  435. //would cause Windows to ask them if they want to format the volume and other dangerous things). */
  436. //if (driveLetter >= 0)
  437. //{
  438. // char rootPath[] = { driveLetter + 'A', ':', '\\', 0 };
  439. // // Try to remove the assigned drive letter
  440. // if (DeleteVolumeMountPoint (rootPath))
  441. // driveLetter = -1;
  442. //}
  443. /* Update config files and app data */
  444. // In the config file, increase the number of partitions where in-place encryption is in progress
  445. SaveNonSysInPlaceEncSettings (1, wipeAlgorithm);
  446. // Add the wizard to the system startup sequence if appropriate
  447. if (!IsNonInstallMode ())
  448. ManageStartupSeqWiz (FALSE, "/prinplace");
  449. nStatus = ERR_SUCCESS;
  450. closing_seq:
  451. dwError = GetLastError();
  452. if (cryptoInfo != NULL)
  453. {
  454. crypto_close (cryptoInfo);
  455. cryptoInfo = NULL;
  456. }
  457. if (cryptoInfo2 != NULL)
  458. {
  459. crypto_close (cryptoInfo2);
  460. cryptoInfo2 = NULL;
  461. }
  462. burn (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
  463. VirtualUnlock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
  464. TCfree (header);
  465. if (dosDev[0])
  466. RemoveFakeDosName (volParams->volumePath, dosDev);
  467. *outHandle = dev;
  468. if (nStatus != ERR_SUCCESS)
  469. SetLastError (dwError);
  470. return nStatus;
  471. }
  472. int EncryptPartitionInPlaceResume (HANDLE dev,
  473. volatile FORMAT_VOL_PARAMETERS *volParams,
  474. WipeAlgorithmId wipeAlgorithm,
  475. volatile BOOL *bTryToCorrectReadErrors)
  476. {
  477. PCRYPTO_INFO masterCryptoInfo = NULL, headerCryptoInfo = NULL, tmpCryptoInfo = NULL;
  478. UINT64_STRUCT unitNo;
  479. char *buf = NULL, *header = NULL;
  480. byte *wipeBuffer = NULL;
  481. byte wipeRandChars [TC_WIPE_RAND_CHAR_COUNT];
  482. byte wipeRandCharsUpdate [TC_WIPE_RAND_CHAR_COUNT];
  483. char dosDev[TC_MAX_PATH] = {0};
  484. char devName[MAX_PATH] = {0};
  485. WCHAR deviceName[MAX_PATH];
  486. int nStatus = ERR_SUCCESS;
  487. __int64 deviceSize;
  488. uint64 remainingBytes, lastHeaderUpdateDistance = 0, zeroedSectorCount = 0;
  489. uint32 workChunkSize;
  490. DWORD dwError, dwResult;
  491. BOOL bPause = FALSE, bEncryptedAreaSizeChanged = FALSE;
  492. LARGE_INTEGER offset;
  493. int sectorSize;
  494. int i;
  495. DWORD n;
  496. char *devicePath = volParams->volumePath;
  497. Password *password = volParams->password;
  498. DISK_GEOMETRY driveGeometry;
  499. bInPlaceEncNonSysResumed = TRUE;
  500. buf = (char *) TCalloc (TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE);
  501. if (!buf)
  502. {
  503. nStatus = ERR_OUTOFMEMORY;
  504. goto closing_seq;
  505. }
  506. header = (char *) TCalloc (TC_VOLUME_HEADER_EFFECTIVE_SIZE);
  507. if (!header)
  508. {
  509. nStatus = ERR_OUTOFMEMORY;
  510. goto closing_seq;
  511. }
  512. VirtualLock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
  513. if (wipeAlgorithm != TC_WIPE_NONE)
  514. {
  515. wipeBuffer = (byte *) TCalloc (TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE);
  516. if (!wipeBuffer)
  517. {
  518. nStatus = ERR_OUTOFMEMORY;
  519. goto closing_seq;
  520. }
  521. }
  522. headerCryptoInfo = crypto_open();
  523. if (headerCryptoInfo == NULL)
  524. {
  525. nStatus = ERR_OUTOFMEMORY;
  526. goto closing_seq;
  527. }
  528. deviceSize = GetDeviceSize (devicePath);
  529. if (deviceSize < 0)
  530. {
  531. // Cannot determine the size of the partition
  532. nStatus = ERR_OS_ERROR;
  533. goto closing_seq;
  534. }
  535. if (dev == INVALID_HANDLE_VALUE)
  536. {
  537. strcpy ((char *)deviceName, devicePath);
  538. ToUNICODE ((char *)deviceName);
  539. if (FakeDosNameForDevice (devicePath, dosDev, devName, FALSE) != 0)
  540. {
  541. nStatus = ERR_OS_ERROR;
  542. goto closing_seq;
  543. }
  544. dev = OpenPartitionVolume (devName,
  545. FALSE, // Do not require exclusive access
  546. FALSE, // Do not require shared access
  547. TRUE, // Ask the user to confirm shared access (if exclusive fails)
  548. FALSE, // Do not append alternative instructions how to encrypt the data (to applicable error messages)
  549. FALSE); // Non-silent mode
  550. if (dev == INVALID_HANDLE_VALUE)
  551. {
  552. nStatus = ERR_DONT_REPORT;
  553. goto closing_seq;
  554. }
  555. }
  556. // This should never be needed, but is still performed for extra safety (without checking the result)
  557. DeviceIoControl (dev,
  558. FSCTL_ALLOW_EXTENDED_DASD_IO,
  559. NULL,
  560. 0,
  561. NULL,
  562. 0,
  563. &dwResult,
  564. NULL);
  565. if (!DeviceIoControl (dev, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &driveGeometry, sizeof (driveGeometry), &dwResult, NULL))
  566. {
  567. nStatus = ERR_OS_ERROR;
  568. goto closing_seq;
  569. }
  570. sectorSize = driveGeometry.BytesPerSector;
  571. nStatus = OpenBackupHeader (dev, devicePath, password, &masterCryptoInfo, headerCryptoInfo, deviceSize);
  572. if (nStatus != ERR_SUCCESS)
  573. goto closing_seq;
  574. remainingBytes = masterCryptoInfo->VolumeSize.Value - masterCryptoInfo->EncryptedAreaLength.Value;
  575. lastHeaderUpdateDistance = 0;
  576. ExportProgressStats (masterCryptoInfo->EncryptedAreaLength.Value, masterCryptoInfo->VolumeSize.Value);
  577. SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_ENCRYPTING);
  578. bFirstNonSysInPlaceEncResumeDone = TRUE;
  579. /* The in-place encryption core */
  580. while (remainingBytes > 0)
  581. {
  582. workChunkSize = (uint32) min (remainingBytes, TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE);
  583. if (workChunkSize % ENCRYPTION_DATA_UNIT_SIZE != 0)
  584. {
  585. nStatus = ERR_PARAMETER_INCORRECT;
  586. goto closing_seq;
  587. }
  588. unitNo.Value = (remainingBytes - workChunkSize + TC_VOLUME_DATA_OFFSET) / ENCRYPTION_DATA_UNIT_SIZE;
  589. // Read the plaintext into RAM
  590. inplace_enc_read:
  591. offset.QuadPart = masterCryptoInfo->EncryptedAreaStart.Value - workChunkSize - TC_VOLUME_DATA_OFFSET;
  592. if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0)
  593. {
  594. nStatus = ERR_OS_ERROR;
  595. goto closing_seq;
  596. }
  597. if (ReadFile (dev, buf, workChunkSize, &n, NULL) == 0)
  598. {
  599. // Read error
  600. DWORD dwTmpErr = GetLastError ();
  601. if (IsDiskReadError (dwTmpErr) && !bVolTransformThreadCancel)
  602. {
  603. // Physical defect or data corruption
  604. if (!*bTryToCorrectReadErrors)
  605. {
  606. *bTryToCorrectReadErrors = (AskWarnYesNo ("ENABLE_BAD_SECTOR_ZEROING") == IDYES);
  607. }
  608. if (*bTryToCorrectReadErrors)
  609. {
  610. // Try to correct the read errors physically
  611. offset.QuadPart = masterCryptoInfo->EncryptedAreaStart.Value - workChunkSize - TC_VOLUME_DATA_OFFSET;
  612. nStatus = ZeroUnreadableSectors (dev, offset, workChunkSize, sectorSize, &zeroedSectorCount);
  613. if (nStatus != ERR_SUCCESS)
  614. {
  615. // Due to write errors, we can't correct the read errors
  616. nStatus = ERR_OS_ERROR;
  617. goto closing_seq;
  618. }
  619. goto inplace_enc_read;
  620. }
  621. }
  622. SetLastError (dwTmpErr); // Preserve the original error code
  623. nStatus = ERR_OS_ERROR;
  624. goto closing_seq;
  625. }
  626. if (remainingBytes - workChunkSize < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE)
  627. {
  628. // We reached the inital portion of the filesystem, which we had concealed (in order to prevent
  629. // Windows from interfering with the volume). Now we need to undo that modification.
  630. for (i = 0; i < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE - (remainingBytes - workChunkSize); i++)
  631. buf[i] ^= TC_NTFS_CONCEAL_CONSTANT;
  632. }
  633. // Encrypt the plaintext in RAM
  634. EncryptDataUnits ((byte *) buf, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, masterCryptoInfo);
  635. // If enabled, wipe the area to which we will write the ciphertext
  636. if (wipeAlgorithm != TC_WIPE_NONE)
  637. {
  638. byte wipePass;
  639. offset.QuadPart = masterCryptoInfo->EncryptedAreaStart.Value - workChunkSize;
  640. for (wipePass = 1; wipePass <= GetWipePassCount (wipeAlgorithm); ++wipePass)
  641. {
  642. if (!WipeBuffer (wipeAlgorithm, wipeRandChars, wipePass, wipeBuffer, workChunkSize))
  643. {
  644. ULONG i;
  645. for (i = 0; i < workChunkSize; ++i)
  646. {
  647. wipeBuffer[i] = buf[i] + wipePass;
  648. }
  649. EncryptDataUnits (wipeBuffer, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, masterCryptoInfo);
  650. memcpy (wipeRandCharsUpdate, wipeBuffer, sizeof (wipeRandCharsUpdate));
  651. }
  652. if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0
  653. || WriteFile (dev, wipeBuffer, workChunkSize, &n, NULL) == 0)
  654. {
  655. // Write error
  656. dwError = GetLastError();
  657. // Undo failed write operation
  658. if (workChunkSize > TC_VOLUME_DATA_OFFSET && SetFilePointerEx (dev, offset, NULL, FILE_BEGIN))
  659. {
  660. DecryptDataUnits ((byte *) buf, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, masterCryptoInfo);
  661. WriteFile (dev, buf + TC_VOLUME_DATA_OFFSET, workChunkSize - TC_VOLUME_DATA_OFFSET, &n, NULL);
  662. }
  663. SetLastError (dwError);
  664. nStatus = ERR_OS_ERROR;
  665. goto closing_seq;
  666. }
  667. }
  668. memcpy (wipeRandChars, wipeRandCharsUpdate, sizeof (wipeRandCharsUpdate));
  669. }
  670. // Write the ciphertext
  671. offset.QuadPart = masterCryptoInfo->EncryptedAreaStart.Value - workChunkSize;
  672. if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0)
  673. {
  674. nStatus = ERR_OS_ERROR;
  675. goto closing_seq;
  676. }
  677. if (WriteFile (dev, buf, workChunkSize, &n, NULL) == 0)
  678. {
  679. // Write error
  680. dwError = GetLastError();
  681. // Undo failed write operation
  682. if (workChunkSize > TC_VOLUME_DATA_OFFSET && SetFilePointerEx (dev, offset, NULL, FILE_BEGIN))
  683. {
  684. DecryptDataUnits ((byte *) buf, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, masterCryptoInfo);
  685. WriteFile (dev, buf + TC_VOLUME_DATA_OFFSET, workChunkSize - TC_VOLUME_DATA_OFFSET, &n, NULL);
  686. }
  687. SetLastError (dwError);
  688. nStatus = ERR_OS_ERROR;
  689. goto closing_seq;
  690. }
  691. masterCryptoInfo->EncryptedAreaStart.Value -= workChunkSize;
  692. masterCryptoInfo->EncryptedAreaLength.Value += workChunkSize;
  693. remainingBytes -= workChunkSize;
  694. lastHeaderUpdateDistance += workChunkSize;
  695. bEncryptedAreaSizeChanged = TRUE;
  696. if (lastHeaderUpdateDistance >= TC_NONSYS_INPLACE_ENC_HEADER_UPDATE_INTERVAL)
  697. {
  698. nStatus = FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize);
  699. if (nStatus != ERR_SUCCESS)
  700. goto closing_seq;
  701. lastHeaderUpdateDistance = 0;
  702. }
  703. ExportProgressStats (masterCryptoInfo->EncryptedAreaLength.Value, masterCryptoInfo->VolumeSize.Value);
  704. if (bVolTransformThreadCancel)
  705. {
  706. bPause = TRUE;
  707. break;
  708. }
  709. }
  710. nStatus = FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize);
  711. if (nStatus != ERR_SUCCESS)
  712. goto closing_seq;
  713. if (!bPause)
  714. {
  715. /* The data area has been fully encrypted; create and write the primary volume header */
  716. SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_FINALIZING);
  717. for (int wipePass = 0; wipePass < (wipeAlgorithm == TC_WIPE_NONE ? 1 : PRAND_DISK_WIPE_PASSES); wipePass++)
  718. {
  719. nStatus = CreateVolumeHeaderInMemory (FALSE,
  720. header,
  721. headerCryptoInfo->ea,
  722. headerCryptoInfo->mode,
  723. password,
  724. masterCryptoInfo->pkcs5,
  725. (char *) masterCryptoInfo->master_keydata,
  726. &tmpCryptoInfo,
  727. masterCryptoInfo->VolumeSize.Value,
  728. 0,
  729. masterCryptoInfo->EncryptedAreaStart.Value,
  730. masterCryptoInfo->EncryptedAreaLength.Value,
  731. masterCryptoInfo->RequiredProgramVersion,
  732. masterCryptoInfo->HeaderFlags | TC_HEADER_FLAG_NONSYS_INPLACE_ENC,
  733. masterCryptoInfo->SectorSize,
  734. wipeAlgorithm == TC_WIPE_NONE ? FALSE : (wipePass < PRAND_DISK_WIPE_PASSES - 1));
  735. if (nStatus != ERR_SUCCESS)
  736. goto closing_seq;
  737. offset.QuadPart = TC_VOLUME_HEADER_OFFSET;
  738. if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0
  739. || !WriteEffectiveVolumeHeader (TRUE, dev, (byte *) header))
  740. {
  741. nStatus = ERR_OS_ERROR;
  742. goto closing_seq;
  743. }
  744. // Fill the reserved sectors of the header area with random data
  745. nStatus = WriteRandomDataToReservedHeaderAreas (dev, headerCryptoInfo, masterCryptoInfo->VolumeSize.Value, TRUE, FALSE);
  746. if (nStatus != ERR_SUCCESS)
  747. goto closing_seq;
  748. }
  749. // Update the configuration files
  750. SaveNonSysInPlaceEncSettings (-1, wipeAlgorithm);
  751. SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_FINISHED);
  752. nStatus = ERR_SUCCESS;
  753. }
  754. else
  755. {
  756. // The process has been paused by the user or aborted by the wizard (e.g. on app exit)
  757. nStatus = ERR_USER_ABORT;
  758. SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_PAUSED);
  759. }
  760. closing_seq:
  761. dwError = GetLastError();
  762. if (bEncryptedAreaSizeChanged
  763. && dev != INVALID_HANDLE_VALUE
  764. && masterCryptoInfo != NULL
  765. && headerCryptoInfo != NULL
  766. && deviceSize > 0)
  767. {
  768. // Execution of the core loop may have been interrupted due to an error or user action without updating the header
  769. FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize);
  770. }
  771. if (masterCryptoInfo != NULL)
  772. {
  773. crypto_close (masterCryptoInfo);
  774. masterCryptoInfo = NULL;
  775. }
  776. if (headerCryptoInfo != NULL)
  777. {
  778. crypto_close (headerCryptoInfo);
  779. headerCryptoInfo = NULL;
  780. }
  781. if (tmpCryptoInfo != NULL)
  782. {
  783. crypto_close (tmpCryptoInfo);
  784. tmpCryptoInfo = NULL;
  785. }
  786. if (dosDev[0])
  787. RemoveFakeDosName (devicePath, dosDev);
  788. if (dev != INVALID_HANDLE_VALUE)
  789. {
  790. CloseHandle (dev);
  791. dev = INVALID_HANDLE_VALUE;
  792. }
  793. if (buf != NULL)
  794. TCfree (buf);
  795. if (header != NULL)
  796. {
  797. burn (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
  798. VirtualUnlock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
  799. TCfree (header);
  800. }
  801. if (wipeBuffer != NULL)
  802. TCfree (wipeBuffer);
  803. if (zeroedSectorCount > 0)
  804. {
  805. wchar_t msg[30000] = {0};
  806. wchar_t sizeStr[500] = {0};
  807. GetSizeString (zeroedSectorCount * sectorSize, sizeStr);
  808. wsprintfW (msg,
  809. GetString ("ZEROED_BAD_SECTOR_COUNT"),
  810. zeroedSectorCount,
  811. sizeStr);
  812. WarningDirect (msg);
  813. }
  814. if (nStatus != ERR_SUCCESS && nStatus != ERR_USER_ABORT)
  815. SetLastError (dwError);
  816. return nStatus;
  817. }
  818. int FastVolumeHeaderUpdate (HANDLE dev, CRYPTO_INFO *headerCryptoInfo, CRYPTO_INFO *masterCryptoInfo, __int64 deviceSize)
  819. {
  820. LARGE_INTEGER offset;
  821. DWORD n;
  822. int nStatus = ERR_SUCCESS;
  823. byte *header;
  824. DWORD dwError;
  825. uint32 headerCrc32;
  826. byte *fieldPos;
  827. header = (byte *) TCalloc (TC_VOLUME_HEADER_EFFECTIVE_SIZE);
  828. if (!header)
  829. return ERR_OUTOFMEMORY;
  830. VirtualLock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
  831. fieldPos = (byte *) header + TC_HEADER_OFFSET_ENCRYPTED_AREA_START;
  832. offset.QuadPart = deviceSize - TC_VOLUME_HEADER_GROUP_SIZE;
  833. if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0
  834. || !ReadEffectiveVolumeHeader (TRUE, dev, header, &n) || n < TC_VOLUME_HEADER_EFFECTIVE_SIZE)
  835. {
  836. nStatus = ERR_OS_ERROR;
  837. goto closing_seq;
  838. }
  839. DecryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, headerCryptoInfo);
  840. if (GetHeaderField32 (header, TC_HEADER_OFFSET_MAGIC) != 0x54525545)
  841. {
  842. nStatus = ERR_PARAMETER_INCORRECT;
  843. goto closing_seq;
  844. }
  845. mputInt64 (fieldPos, (masterCryptoInfo->EncryptedAreaStart.Value));
  846. mputInt64 (fieldPos, (masterCryptoInfo->EncryptedAreaLength.Value));
  847. headerCrc32 = GetCrc32 (header + TC_HEADER_OFFSET_MAGIC, TC_HEADER_OFFSET_HEADER_CRC - TC_HEADER_OFFSET_MAGIC);
  848. fieldPos = (byte *) header + TC_HEADER_OFFSET_HEADER_CRC;
  849. mputLong (fieldPos, headerCrc32);
  850. EncryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, headerCryptoInfo);
  851. if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0
  852. || !WriteEffectiveVolumeHeader (TRUE, dev, header))
  853. {
  854. nStatus = ERR_OS_ERROR;
  855. goto closing_seq;
  856. }
  857. closing_seq:
  858. dwError = GetLastError();
  859. burn (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
  860. VirtualUnlock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
  861. TCfree (header);
  862. if (nStatus != ERR_SUCCESS)
  863. SetLastError (dwError);
  864. return nStatus;
  865. }
  866. static HANDLE OpenPartitionVolume (const char *devName,
  867. BOOL bExclusiveRequired,
  868. BOOL bSharedRequired,
  869. BOOL bSharedRequiresConfirmation,
  870. BOOL bShowAlternativeSteps,
  871. BOOL bSilent)
  872. {
  873. HANDLE dev = INVALID_HANDLE_VALUE;
  874. int retryCount = 0;
  875. if (bExclusiveRequired)
  876. bSharedRequired = FALSE;
  877. if (bExclusiveRequired || !bSharedRequired)
  878. {
  879. // Exclusive access
  880. // Note that when exclusive access is denied, it is worth retrying (usually succeeds after a few tries).
  881. while (dev == INVALID_HANDLE_VALUE && retryCount++ < EXCL_ACCESS_MAX_AUTO_RETRIES)
  882. {
  883. dev = CreateFile (devName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_WRITE_THROUGH, NULL);
  884. if (retryCount > 1)
  885. Sleep (EXCL_ACCESS_AUTO_RETRY_DELAY);
  886. }
  887. }
  888. if (dev == INVALID_HANDLE_VALUE)
  889. {
  890. if (bExclusiveRequired)
  891. {
  892. if (!bSilent)
  893. {
  894. handleWin32Error (MainDlg);
  895. if (bShowAlternativeSteps)
  896. ShowInPlaceEncErrMsgWAltSteps ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE);
  897. else
  898. Error ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL");
  899. }
  900. return INVALID_HANDLE_VALUE;
  901. }
  902. // Shared mode
  903. dev = CreateFile (devName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_WRITE_THROUGH, NULL);
  904. if (dev != INVALID_HANDLE_VALUE)
  905. {
  906. if (bSharedRequiresConfirmation
  907. && !bSilent
  908. && AskWarnNoYes ("DEVICE_IN_USE_INPLACE_ENC") == IDNO)
  909. {
  910. CloseHandle (dev);
  911. return INVALID_HANDLE_VALUE;
  912. }
  913. }
  914. else
  915. {
  916. if (!bSilent)
  917. {
  918. handleWin32Error (MainDlg);
  919. if (bShowAlternativeSteps)
  920. ShowInPlaceEncErrMsgWAltSteps ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE);
  921. else
  922. Error ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL");
  923. }
  924. return INVALID_HANDLE_VALUE;
  925. }
  926. }
  927. return dev;
  928. }
  929. static int DismountFileSystem (HANDLE dev,
  930. int driveLetter,
  931. BOOL bForcedAllowed,
  932. BOOL bForcedRequiresConfirmation,
  933. BOOL bSilent)
  934. {
  935. int attempt;
  936. BOOL bResult;
  937. DWORD dwResult;
  938. CloseVolumeExplorerWindows (MainDlg, driveLetter);
  939. attempt = UNMOUNT_MAX_AUTO_RETRIES * 10;
  940. while (!(bResult = DeviceIoControl (dev, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &dwResult, NULL))
  941. && attempt > 0)
  942. {
  943. Sleep (UNMOUNT_AUTO_RETRY_DELAY);
  944. attempt--;
  945. }
  946. if (!bResult)
  947. {
  948. if (!bForcedAllowed)
  949. {
  950. if (!bSilent)
  951. ShowInPlaceEncErrMsgWAltSteps ("INPLACE_ENC_CANT_LOCK_OR_DISMOUNT_FILESYS", TRUE);
  952. return ERR_DONT_REPORT;
  953. }
  954. if (bForcedRequiresConfirmation
  955. && !bSilent
  956. && AskWarnYesNo ("VOL_LOCK_FAILED_OFFER_FORCED_DISMOUNT") == IDNO)
  957. {
  958. return ERR_DONT_REPORT;
  959. }
  960. }
  961. // Dismount the volume
  962. attempt = UNMOUNT_MAX_AUTO_RETRIES * 10;
  963. while (!(bResult = DeviceIoControl (dev, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, &dwResult, NULL))
  964. && attempt > 0)
  965. {
  966. Sleep (UNMOUNT_AUTO_RETRY_DELAY);
  967. attempt--;
  968. }
  969. if (!bResult)
  970. {
  971. if (!bSilent)
  972. ShowInPlaceEncErrMsgWAltSteps ("INPLACE_ENC_CANT_LOCK_OR_DISMOUNT_FILESYS", TRUE);
  973. return ERR_DONT_REPORT;
  974. }
  975. return ERR_SUCCESS;
  976. }
  977. // Easy-to-undo modification applied to conceal the NTFS filesystem (to prevent Windows and apps from
  978. // interfering with it until the volume has been fully encrypted). Note that this function will precisely
  979. // undo any modifications it made to the filesystem automatically if an error occurs when writing (including
  980. // physical drive defects).
  981. static int ConcealNTFS (HANDLE dev)
  982. {
  983. char buf [TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE];
  984. DWORD nbrBytesProcessed, nbrBytesProcessed2;
  985. int i;
  986. LARGE_INTEGER offset;
  987. DWORD dwError;
  988. offset.QuadPart = 0;
  989. if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0)
  990. return ERR_OS_ERROR;
  991. if (ReadFile (dev, buf, TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE, &nbrBytesProcessed, NULL) == 0)
  992. return ERR_OS_ERROR;
  993. for (i = 0; i < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE; i++)
  994. buf[i] ^= TC_NTFS_CONCEAL_CONSTANT;
  995. offset.QuadPart = 0;
  996. if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0)
  997. return ERR_OS_ERROR;
  998. if (WriteFile (dev, buf, TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE, &nbrBytesProcessed, NULL) == 0)
  999. {
  1000. // One or more of the sectors is/are probably damaged and cause write errors.
  1001. // We must undo the modifications we made.
  1002. dwError = GetLastError();
  1003. for (i = 0; i < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE; i++)
  1004. buf[i] ^= TC_NTFS_CONCEAL_CONSTANT;
  1005. offset.QuadPart = 0;
  1006. do
  1007. {
  1008. Sleep (1);
  1009. }
  1010. while (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0
  1011. || WriteFile (dev, buf, TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE, &nbrBytesProcessed2, NULL) == 0);
  1012. SetLastError (dwError);
  1013. return ERR_OS_ERROR;
  1014. }
  1015. return ERR_SUCCESS;
  1016. }
  1017. void ShowInPlaceEncErrMsgWAltSteps (char *iniStrId, BOOL bErr)
  1018. {
  1019. wchar_t msg[30000];
  1020. wcscpy (msg, GetString (iniStrId));
  1021. wcscat (msg, L"\n\n\n");
  1022. wcscat (msg, GetString ("INPLACE_ENC_ALTERNATIVE_STEPS"));
  1023. if (bErr)
  1024. ErrorDirect (msg);
  1025. else
  1026. WarningDirect (msg);
  1027. }
  1028. static void ExportProgressStats (__int64 bytesDone, __int64 totalSize)
  1029. {
  1030. NonSysInplaceEncBytesDone = bytesDone;
  1031. NonSysInplaceEncTotalSize = totalSize;
  1032. }
  1033. void SetNonSysInplaceEncUIStatus (int nonSysInplaceEncStatus)
  1034. {
  1035. NonSysInplaceEncStatus = nonSysInplaceEncStatus;
  1036. }
  1037. BOOL SaveNonSysInPlaceEncSettings (int delta, WipeAlgorithmId newWipeAlgorithm)
  1038. {
  1039. int count;
  1040. char str[32];
  1041. WipeAlgorithmId savedWipeAlgorithm = TC_WIPE_NONE;
  1042. if (delta == 0)
  1043. return TRUE;
  1044. count = LoadNonSysInPlaceEncSettings (&savedWipeAlgorithm) + delta;
  1045. if (count < 1)
  1046. {
  1047. RemoveNonSysInPlaceEncNotifications();
  1048. return TRUE;
  1049. }
  1050. else
  1051. {
  1052. if (newWipeAlgorithm != TC_WIPE_NONE)
  1053. {
  1054. sprintf (str, "%d", (int) newWipeAlgorithm);
  1055. SaveBufferToFile (str, GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE), strlen(str), FALSE);
  1056. }
  1057. else if (FileExists (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE)))
  1058. {
  1059. remove (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE));
  1060. }
  1061. sprintf (str, "%d", count);
  1062. return SaveBufferToFile (str, GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC), strlen(str), FALSE);
  1063. }
  1064. }
  1065. // Repairs damaged sectors (i.e. those with read errors) by zeroing them.
  1066. // Note that this operating fails if there are any write errors.
  1067. int ZeroUnreadableSectors (HANDLE dev, LARGE_INTEGER startOffset, int64 size, int sectorSize, uint64 *zeroedSectorCount)
  1068. {
  1069. int nStatus;
  1070. DWORD n;
  1071. int64 sectorCount;
  1072. LARGE_INTEGER workOffset;
  1073. byte *sectorBuffer = NULL;
  1074. DWORD dwError;
  1075. workOffset.QuadPart = startOffset.QuadPart;
  1076. sectorBuffer = (byte *) TCalloc (sectorSize);
  1077. if (!sectorBuffer)
  1078. return ERR_OUTOFMEMORY;
  1079. if (SetFilePointerEx (dev, startOffset, NULL, FILE_BEGIN) == 0)
  1080. {
  1081. nStatus = ERR_OS_ERROR;
  1082. goto closing_seq;
  1083. }
  1084. for (sectorCount = size / sectorSize; sectorCount > 0; --sectorCount)
  1085. {
  1086. if (ReadFile (dev, sectorBuffer, sectorSize, &n, NULL) == 0)
  1087. {
  1088. memset (sectorBuffer, 0, sectorSize);
  1089. if (SetFilePointerEx (dev, workOffset, NULL, FILE_BEGIN) == 0)
  1090. {
  1091. nStatus = ERR_OS_ERROR;
  1092. goto closing_seq;
  1093. }
  1094. if (WriteFile (dev, sectorBuffer, sectorSize, &n, NULL) == 0)
  1095. {
  1096. nStatus = ERR_OS_ERROR;
  1097. goto closing_seq;
  1098. }
  1099. ++(*zeroedSectorCount);
  1100. }
  1101. workOffset.QuadPart += n;
  1102. }
  1103. nStatus = ERR_SUCCESS;
  1104. closing_seq:
  1105. dwError = GetLastError();
  1106. if (sectorBuffer != NULL)
  1107. TCfree (sectorBuffer);
  1108. if (nStatus != ERR_SUCCESS)
  1109. SetLastError (dwError);
  1110. return nStatus;
  1111. }
  1112. static int OpenBackupHeader (HANDLE dev, const char *devicePath, Password *password, PCRYPTO_INFO *retMasterCryptoInfo, CRYPTO_INFO *headerCryptoInfo, __int64 deviceSize)
  1113. {
  1114. LARGE_INTEGER offset;
  1115. DWORD n;
  1116. int nStatus = ERR_SUCCESS;
  1117. char *header;
  1118. DWORD dwError;
  1119. header = (char *) TCalloc (TC_VOLUME_HEADER_EFFECTIVE_SIZE);
  1120. if (!header)
  1121. return ERR_OUTOFMEMORY;
  1122. VirtualLock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
  1123. offset.QuadPart = deviceSize - TC_VOLUME_HEADER_GROUP_SIZE;
  1124. if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0
  1125. || !ReadEffectiveVolumeHeader (TRUE, dev, (byte *) header, &n) || n < TC_VOLUME_HEADER_EFFECTIVE_SIZE)
  1126. {
  1127. nStatus = ERR_OS_ERROR;
  1128. goto closing_seq;
  1129. }
  1130. nStatus = ReadVolumeHeader (FALSE, header, password, retMasterCryptoInfo, headerCryptoInfo);
  1131. if (nStatus != ERR_SUCCESS)
  1132. goto closing_seq;
  1133. closing_seq:
  1134. dwError = GetLastError();
  1135. burn (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
  1136. VirtualUnlock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
  1137. TCfree (header);
  1138. dwError = GetLastError();
  1139. if (nStatus != ERR_SUCCESS)
  1140. SetLastError (dwError);
  1141. return nStatus;
  1142. }
  1143. static BOOL GetFreeClusterBeforeThreshold (HANDLE volumeHandle, int64 *freeCluster, int64 clusterThreshold)
  1144. {
  1145. const int bitmapSize = 65536;
  1146. byte bitmapBuffer[bitmapSize + sizeof (VOLUME_BITMAP_BUFFER)];
  1147. VOLUME_BITMAP_BUFFER *bitmap = (VOLUME_BITMAP_BUFFER *) bitmapBuffer;
  1148. STARTING_LCN_INPUT_BUFFER startLcn;
  1149. startLcn.StartingLcn.QuadPart = 0;
  1150. DWORD bytesReturned;
  1151. while (DeviceIoControl (volumeHandle, FSCTL_GET_VOLUME_BITMAP, &startLcn, sizeof (startLcn), &bitmapBuffer, sizeof (bitmapBuffer), &bytesReturned, NULL)
  1152. || GetLastError() == ERROR_MORE_DATA)
  1153. {
  1154. for (int64 bitmapIndex = 0; bitmapIndex < min (bitmapSize, (bitmap->BitmapSize.QuadPart / 8)); ++bitmapIndex)
  1155. {
  1156. if (bitmap->StartingLcn.QuadPart + bitmapIndex * 8 >= clusterThreshold)
  1157. goto err;
  1158. if (bitmap->Buffer[bitmapIndex] != 0xff)
  1159. {
  1160. for (int bit = 0; bit < 8; ++bit)
  1161. {
  1162. if ((bitmap->Buffer[bitmapIndex] & (1 << bit)) == 0)
  1163. {
  1164. *freeCluster = bitmap->StartingLcn.QuadPart + bitmapIndex * 8 + bit;
  1165. if (*freeCluster >= clusterThreshold)
  1166. goto err;
  1167. return TRUE;
  1168. }
  1169. }
  1170. }
  1171. }
  1172. startLcn.StartingLcn.QuadPart += min (bitmapSize * 8, bitmap->BitmapSize.QuadPart);
  1173. }
  1174. err:
  1175. SetLastError (ERROR_DISK_FULL);
  1176. return FALSE;
  1177. }
  1178. static BOOL MoveClustersBeforeThresholdInDir (HANDLE volumeHandle, const wstring &directory, int64 clusterThreshold)
  1179. {
  1180. WIN32_FIND_DATAW findData;
  1181. HANDLE findHandle = FindFirstFileW (((directory.size() <= 3 ? L"" : L"\\\\?\\") + directory + L"\\*").c_str(), &findData);
  1182. if (findHandle == INVALID_HANDLE_VALUE)
  1183. return TRUE; // Error ignored
  1184. finally_do_arg (HANDLE, findHandle, { FindClose (finally_arg); });
  1185. // Find all files and directories
  1186. do
  1187. {
  1188. if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  1189. {
  1190. wstring subDir = findData.cFileName;
  1191. if (subDir == L"." || subDir == L"..")
  1192. continue;
  1193. if (!MoveClustersBeforeThresholdInDir (volumeHandle, directory + L"\\" + subDir, clusterThreshold))
  1194. return FALSE;
  1195. }
  1196. DWORD access = FILE_READ_ATTRIBUTES;
  1197. if (findData.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED)
  1198. access = FILE_READ_DATA;
  1199. HANDLE fsObject = CreateFileW ((directory + L"\\" + findData.cFileName).c_str(), access, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
  1200. if (fsObject == INVALID_HANDLE_VALUE)
  1201. continue;
  1202. finally_do_arg (HANDLE, fsObject, { CloseHandle (finally_arg); });
  1203. STARTING_VCN_INPUT_BUFFER startVcn;
  1204. startVcn.StartingVcn.QuadPart = 0;
  1205. RETRIEVAL_POINTERS_BUFFER retPointers;
  1206. DWORD bytesReturned;
  1207. // Find clusters allocated beyond the threshold
  1208. while (DeviceIoControl (fsObject, FSCTL_GET_RETRIEVAL_POINTERS, &startVcn, sizeof (startVcn), &retPointers, sizeof (retPointers), &bytesReturned, NULL)
  1209. || GetLastError() == ERROR_MORE_DATA)
  1210. {
  1211. if (retPointers.ExtentCount == 0)
  1212. break;
  1213. if (retPointers.Extents[0].Lcn.QuadPart != -1)
  1214. {
  1215. int64 extentStartCluster = retPointers.Extents[0].Lcn.QuadPart;
  1216. int64 extentLen = retPointers.Extents[0].NextVcn.QuadPart - retPointers.StartingVcn.QuadPart;
  1217. int64 extentEndCluster = extentStartCluster + extentLen - 1;
  1218. if (extentEndCluster >= clusterThreshold)
  1219. {
  1220. // Move clusters before the threshold
  1221. for (int64 movedCluster = max (extentStartCluster, clusterThreshold); movedCluster <= extentEndCluster; ++movedCluster)
  1222. {
  1223. for (int retry = 0; ; ++retry)
  1224. {
  1225. MOVE_FILE_DATA moveData;
  1226. if (GetFreeClusterBeforeThreshold (volumeHandle, &moveData.StartingLcn.QuadPart, clusterThreshold))
  1227. {
  1228. moveData.FileHandle = fsObject;
  1229. moveData.StartingVcn.QuadPart = movedCluster - extentStartCluster + retPointers.StartingVcn.QuadPart;
  1230. moveData.ClusterCount = 1;
  1231. if (DeviceIoControl (volumeHandle, FSCTL_MOVE_FILE, &moveData, sizeof (moveData), NULL, 0, &bytesReturned, NULL))
  1232. break;
  1233. }
  1234. if (retry > 600)
  1235. return FALSE;
  1236. // There are possible race conditions as we work on a live filesystem
  1237. Sleep (100);
  1238. }
  1239. }
  1240. }
  1241. }
  1242. startVcn.StartingVcn = retPointers.Extents[0].NextVcn;
  1243. }
  1244. } while (FindNextFileW (findHandle, &findData));
  1245. return TRUE;
  1246. }
  1247. BOOL MoveClustersBeforeThreshold (HANDLE volumeHandle, PWSTR volumeDevicePath, int64 clusterThreshold)
  1248. {
  1249. int drive = GetDiskDeviceDriveLetter (volumeDevicePath);
  1250. if (drive == -1)
  1251. {
  1252. SetLastError (ERROR_INVALID_PARAMETER);
  1253. return FALSE;
  1254. }
  1255. wstring volumeRoot = L"X:";
  1256. volumeRoot[0] = L'A' + (wchar_t) drive;
  1257. return MoveClustersBeforeThresholdInDir (volumeHandle, volumeRoot, clusterThreshold);
  1258. }