/* Legal Notice: Some portions of the source code contained in this file were derived from the source code of Encryption for the Masses 2.02a, which is Copyright (c) 1998-2000 Paul Le Roux and which is governed by the 'License Agreement for Encryption for the Masses'. Modifications and additions to the original source code (contained in this file) and all other portions of this file are Copyright (c) 2003-2010 TrueCrypt Developers Association and are governed by the TrueCrypt License 3.0 the full text of which is contained in the file License.txt included in TrueCrypt binary and source code distribution packages. */ #include #include #include "Tcdefs.h" #include "Common.h" #include "Crypto.h" #include "Fat.h" #include "Format.h" #include "Random.h" #include "Volumes.h" #include "Apidrvr.h" #include "Dlgcode.h" #include "Language.h" #include "Progress.h" #include "Resource.h" #include "Format/FormatCom.h" #include "Format/Tcformat.h" #include int FormatWriteBufferSize = 1024 * 1024; static uint32 FormatSectorSize = 0; uint64 GetVolumeDataAreaSize (BOOL hiddenVolume, uint64 volumeSize) { uint64 reservedSize; if (hiddenVolume) { // Reserve free space at the end of the host filesystem. FAT file system fills the last sector with // zeroes (marked as free; observed when quick format was performed using the OS format tool). // Therefore, when the outer volume is mounted with hidden volume protection, such write operations // (e.g. quick formatting the outer volume filesystem as FAT) would needlessly trigger hidden volume // protection. #if TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE > 4096 # error TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE too large for very small volumes. Revise the code. #endif #if TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE_HIGH < TC_MAX_VOLUME_SECTOR_SIZE # error TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE_HIGH too small. #endif if (volumeSize < TC_VOLUME_SMALL_SIZE_THRESHOLD) reservedSize = TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE; else reservedSize = TC_HIDDEN_VOLUME_HOST_FS_RESERVED_END_AREA_SIZE_HIGH; // Ensure size of a hidden volume larger than TC_VOLUME_SMALL_SIZE_THRESHOLD is a multiple of the maximum supported sector size } else { reservedSize = TC_TOTAL_VOLUME_HEADERS_SIZE; } if (volumeSize < reservedSize) return 0; return volumeSize - reservedSize; } int TCFormatVolume (volatile FORMAT_VOL_PARAMETERS *volParams) { int nStatus; PCRYPTO_INFO cryptoInfo = NULL; HANDLE dev = INVALID_HANDLE_VALUE; DWORD dwError; char header[TC_VOLUME_HEADER_EFFECTIVE_SIZE]; unsigned __int64 num_sectors, startSector; fatparams ft; FILETIME ftCreationTime; FILETIME ftLastWriteTime; FILETIME ftLastAccessTime; BOOL bTimeStampValid = FALSE; BOOL bInstantRetryOtherFilesys = FALSE; char dosDev[TC_MAX_PATH] = { 0 }; char devName[MAX_PATH] = { 0 }; int driveLetter = -1; WCHAR deviceName[MAX_PATH]; uint64 dataOffset, dataAreaSize; LARGE_INTEGER offset; BOOL bFailedRequiredDASD = FALSE; HWND hwndDlg = volParams->hwndDlg; FormatSectorSize = volParams->sectorSize; if (FormatSectorSize < TC_MIN_VOLUME_SECTOR_SIZE || FormatSectorSize > TC_MAX_VOLUME_SECTOR_SIZE || FormatSectorSize % ENCRYPTION_DATA_UNIT_SIZE != 0) { Error ("SECTOR_SIZE_UNSUPPORTED", hwndDlg); return ERR_DONT_REPORT; } /* WARNING: Note that if Windows fails to format the volume as NTFS and the volume size is less than the maximum FAT size, the user is asked within this function whether he wants to instantly retry FAT format instead (to avoid having to re-create the whole container again). If the user answers yes, some of the input parameters are modified, the code below 'begin_format' is re-executed and some destructive operations that were performed during the first attempt must be (and are) skipped. Therefore, whenever adding or modifying any potentially destructive operations below 'begin_format', determine whether they (or their portions) need to be skipped during such a second attempt; if so, use the 'bInstantRetryOtherFilesys' flag to skip them. */ if (volParams->hiddenVol) { dataOffset = volParams->hiddenVolHostSize - TC_VOLUME_HEADER_GROUP_SIZE - volParams->size; } else { if (volParams->size <= TC_TOTAL_VOLUME_HEADERS_SIZE) return ERR_VOL_SIZE_WRONG; dataOffset = TC_VOLUME_DATA_OFFSET; } dataAreaSize = GetVolumeDataAreaSize (volParams->hiddenVol, volParams->size); num_sectors = dataAreaSize / FormatSectorSize; if (volParams->bDevice) { StringCbCopyA ((char *)deviceName, sizeof(deviceName), volParams->volumePath); ToUNICODE ((char *)deviceName, sizeof(deviceName)); driveLetter = GetDiskDeviceDriveLetter (deviceName); } VirtualLock (header, sizeof (header)); nStatus = CreateVolumeHeaderInMemory (hwndDlg, FALSE, header, volParams->ea, FIRST_MODE_OF_OPERATION_ID, volParam
/*
 Copyright (c) 2008 TrueCrypt Developers Association. All rights reserved.

 Governed by the TrueCrypt License 3.0 the full text of which is contained in
 the file License.txt included in TrueCrypt binary and source code distribution
 packages.
*/

#ifndef TC_HEADER_Encryption_EncryptionModeCBC
#define TC_HEADER_Encryption_EncryptionModeCBC

#include "Platform/Platform.h"
#include "EncryptionMode.h"

namespace VeraCrypt
{
	class EncryptionModeCBC : public EncryptionMode
	{
	public:
		EncryptionModeCBC () { }
		virtual ~EncryptionModeCBC () { }

		virtual void Decrypt (byte *data, uint64 length) const;
		virtual void DecryptSectorsCurrentThread (byte *data, uint64 sectorIndex, uint64 sectorCount, size_t sectorSize) const;
		virtual void Encrypt (byte *data, uint64 length) const;
		virtual void EncryptSectorsCurrentThread (byte *data, uint64 sectorIndex, uint64 sectorCount, size_t sectorSize) const;
		virtual size_t GetKeySize () const { return 32; };
		virtual wstring GetName () const { return L"CBC"; };
		virtual shared_ptr <EncryptionMode> GetNew () const { return shared_ptr <EncryptionMode> (new EncryptionModeCBC); }
		virtual void SetKey (const ConstBufferPtr &key);

	protected:
		void DecryptBuffer (byte *data, uint64 length, const CipherList &ciphers, const uint32 *iv, const uint32 *whitening) const;
		void EncryptBuffer (byte *data, uint64 length, const CipherList &ciphers, const uint32 *iv, const uint32 *whitening) const;
		void InitSectorIVAndWhitening (uint64 sectorIndex, size_t blockSize, const uint64 *ivSeed, uint32 *iv, uint32 *whitening) const;
		bool IsOuterCBC (const CipherList &ciphers) const;

		SecureBuffer IV;
		static const int WhiteningIVOffset = 8;

	private:
		EncryptionModeCBC (const EncryptionModeCBC &);
		EncryptionModeCBC &operator= (const EncryptionModeCBC &);
	};
}

#endif // TC_HEADER_Encryption_EncryptionModeCBC
(volParams->hwndDlg, GetString ("CANT_MOUNT_VOLUME"), lpszTitle, ICON_HAND); MessageBoxW (volParams->hwndDlg, GetString ("FORMAT_NTFS_STOP"), lpszTitle, ICON_HAND); nStatus = ERR_VOL_MOUNT_FAILED; goto fv_end; } if (!IsAdmin () && IsUacSupported ()) retCode = UacFormatNtfs (volParams->hwndDlg, driveNo, volParams->clusterSize); else retCode = FormatNtfs (driveNo, volParams->clusterSize); if (retCode != TRUE) { if (!UnmountVolume (volParams->hwndDlg, driveNo, FALSE)) MessageBoxW (volParams->hwndDlg, GetString ("CANT_DISMOUNT_VOLUME"), lpszTitle, ICON_HAND); if (dataAreaSize <= TC_MAX_FAT_SECTOR_COUNT * FormatSectorSize) { if (AskErrYesNo ("FORMAT_NTFS_FAILED_ASK_FAT", hwndDlg) == IDYES) { // NTFS format failed and the user wants to try FAT format immediately volParams->fileSystem = FILESYS_FAT; bInstantRetryOtherFilesys = TRUE; volParams->quickFormat = TRUE; // Volume has already been successfully TC-formatted volParams->clusterSize = 0; // Default cluster size goto begin_format; } } else Error ("FORMAT_NTFS_FAILED", hwndDlg); nStatus = ERR_DONT_REPORT; goto fv_end; } if (!UnmountVolume (volParams->hwndDlg, driveNo, FALSE)) MessageBoxW (volParams->hwndDlg, GetString ("CANT_DISMOUNT_VOLUME"), lpszTitle, ICON_HAND); } fv_end: dwError = GetLastError(); if (dosDev[0]) RemoveFakeDosName (volParams->volumePath, dosDev); crypto_close (cryptoInfo); SetLastError (dwError); return nStatus; } int FormatNoFs (HWND hwndDlg, unsigned __int64 startSector, __int64 num_sectors, void * dev, PCRYPTO_INFO cryptoInfo, BOOL quickFormat) { int write_buf_cnt = 0; char sector[TC_MAX_VOLUME_SECTOR_SIZE], *write_buf; unsigned __int64 nSecNo = startSector; int retVal = 0; DWORD err; char temporaryKey[MASTER_KEYDATA_SIZE]; char originalK2[MASTER_KEYDATA_SIZE]; LARGE_INTEGER startOffset; LARGE_INTEGER newOffset; // Seek to start sector startOffset.QuadPart = startSector * FormatSectorSize; if (!SetFilePointerEx ((HANDLE) dev, startOffset, &newOffset, FILE_BEGIN) || newOffset.QuadPart != startOffset.QuadPart) { return ERR_OS_ERROR; } write_buf = (char *)TCalloc (FormatWriteBufferSize); if (!write_buf) return ERR_OUTOFMEMORY; VirtualLock (temporaryKey, sizeof (temporaryKey)); VirtualLock (originalK2, sizeof (originalK2)); memset (sector, 0, sizeof (sector)); // Remember the original secondary key (XTS mode) before generating a temporary one memcpy (originalK2, cryptoInfo->k2, sizeof (cryptoInfo->k2)); /* Fill the rest of the data area with random data */ if(!quickFormat) { /* Generate a random temporary key set to be used for "dummy" encryption that will fill the free disk space (data area) with random data. This is necessary for plausible deniability of hidden volumes. */ // Temporary master key if (!RandgetBytes (hwndDlg, temporaryKey, EAGetKeySize (cryptoInfo->ea), FALSE)) goto fail; // Temporary secondary key (XTS mode) if (!RandgetBytes (hwndDlg, cryptoInfo->k2, sizeof cryptoInfo->k2, FALSE)) goto fail; retVal = EAInit (cryptoInfo->ea, temporaryKey, cryptoInfo->ks); if (retVal != ERR_SUCCESS) goto fail; if (!EAInitMode (cryptoInfo)) { retVal = ERR_MODE_INIT_FAILED; goto fail; } while (num_sectors--) { if (WriteSector (dev, sector, write_buf, &write_buf_cnt, &nSecNo, cryptoInfo) == FALSE) goto fail; } if (!FlushFormatWriteBuffer (dev, write_buf, &write_buf_cnt, &nSecNo, cryptoInfo)) goto fail; } else nSecNo = num_sectors; UpdateProgressBar (nSecNo * FormatSectorSize); // Restore the original secondary key (XTS mode) in case NTFS format fails and the user wants to try FAT immediately memcpy (cryptoInfo->k2, originalK2, sizeof (cryptoInfo->k2)); // Reinitialize the encryption algorithm and mode in case NTFS format fails and the user wants to try FAT immediately retVal = EAInit (cryptoInfo->ea, cryptoInfo->master_keydata, cryptoInfo->ks); if (retVal != ERR_SUCCESS) goto fail; if (!EAInitMode (cryptoInfo)) { retVal = ERR_MODE_INIT_FAILED; goto fail; } burn (temporaryKey, sizeof(temporaryKey)); burn (originalK2, sizeof(originalK2)); VirtualUnlock (temporaryKey, sizeof (temporaryKey)); VirtualUnlock (originalK2, sizeof (originalK2)); TCfree (write_buf); return 0; fail: err = GetLastError(); burn (temporaryKey, sizeof(temporaryKey)); burn (originalK2, sizeof(originalK2)); VirtualUnlock (temporaryKey, sizeof (temporaryKey)); VirtualUnlock (originalK2, sizeof (originalK2)); TCfree (write_buf); SetLastError (err); return (retVal ? retVal : ERR_OS_ERROR); } volatile BOOLEAN FormatExResult; BOOLEAN __stdcall FormatExCallback (int command, DWORD subCommand, PVOID parameter) { if (command == FMIFS_DONE) FormatExResult = *(BOOLEAN *) parameter; return TRUE; } BOOL FormatNtfs (int driveNo, int clusterSize) { char dllPath[MAX_PATH] = {0}; WCHAR dir[8] = { (WCHAR) driveNo + 'A', 0 }; PFORMATEX FormatEx; HMODULE hModule; int i; if (GetSystemDirectory (dllPath, MAX_PATH)) { StringCbCatA(dllPath, sizeof(dllPath), "\\fmifs.dll"); } else StringCbCopyA(dllPath, sizeof(dllPath), "C:\\Windows\\System32\\fmifs.dll"); hModule = LoadLibrary (dllPath); if (hModule == NULL) return FALSE; if (!(FormatEx = (PFORMATEX) GetProcAddress (GetModuleHandle ("fmifs.dll"), "FormatEx"))) { FreeLibrary (hModule); return FALSE; } StringCbCatW (dir, sizeof(dir), L":\\"); FormatExResult = FALSE; // Windows sometimes fails to format a volume (hosted on a removable medium) as NTFS. // It often helps to retry several times. for (i = 0; i < 50 && FormatExResult != TRUE; i++) { FormatEx (dir, FMIFS_HARDDISK, L"NTFS", L"", TRUE, clusterSize * FormatSectorSize, FormatExCallback); } // The device may be referenced for some time after FormatEx() returns Sleep (2000); FreeLibrary (hModule); return FormatExResult; } BOOL WriteSector (void *dev, char *sector, char *write_buf, int *write_buf_cnt, __int64 *nSecNo, PCRYPTO_INFO cryptoInfo) { static __int32 updateTime = 0; (*nSecNo)++; memcpy (write_buf + *write_buf_cnt, sector, FormatSectorSize); (*write_buf_cnt) += FormatSectorSize; if (*write_buf_cnt == FormatWriteBufferSize && !FlushFormatWriteBuffer (dev, write_buf, write_buf_cnt, nSecNo, cryptoInfo)) return FALSE; if (GetTickCount () - updateTime > 25) { if (UpdateProgressBar (*nSecNo * FormatSectorSize)) return FALSE; updateTime = GetTickCount (); } return TRUE; } static volatile BOOL WriteThreadRunning; static volatile BOOL WriteThreadExitRequested; static HANDLE WriteThreadHandle; static byte *WriteThreadBuffer; static HANDLE WriteBufferEmptyEvent; static HANDLE WriteBufferFullEvent; static volatile HANDLE WriteRequestHandle; static volatile int WriteRequestSize; static volatile DWORD WriteRequestResult; static void __cdecl FormatWriteThreadProc (void *arg) { DWORD bytesWritten; SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_HIGHEST); while (!WriteThreadExitRequested) { if (WaitForSingleObject (WriteBufferFullEvent, INFINITE) == WAIT_FAILED) { handleWin32Error (NULL); break; } if (WriteThreadExitRequested) break; if (!WriteFile (WriteRequestHandle, WriteThreadBuffer, WriteRequestSize, &bytesWritten, NULL)) WriteRequestResult = GetLastError(); else WriteRequestResult = ERROR_SUCCESS; if (!SetEvent (WriteBufferEmptyEvent)) { handleWin32Error (NULL); break; } } WriteThreadRunning = FALSE; _endthread(); } static BOOL StartFormatWriteThread () { DWORD sysErr; WriteBufferEmptyEvent = NULL; WriteBufferFullEvent = NULL; WriteThreadBuffer = NULL; WriteBufferEmptyEvent = CreateEvent (NULL, FALSE, TRUE, NULL); if (!WriteBufferEmptyEvent) goto err; WriteBufferFullEvent = CreateEvent (NULL, FALSE, FALSE, NULL); if (!WriteBufferFullEvent) goto err; WriteThreadBuffer = TCalloc (FormatWriteBufferSize); if (!WriteThreadBuffer) { SetLastError (ERROR_OUTOFMEMORY); goto err; } WriteThreadExitRequested = FALSE; WriteRequestResult = ERROR_SUCCESS; WriteThreadHandle = (HANDLE) _beginthread (FormatWriteThreadProc, 0, NULL); if ((uintptr_t) WriteThreadHandle == -1L) goto err; WriteThreadRunning = TRUE; return TRUE; err: sysErr = GetLastError(); if (WriteBufferEmptyEvent) CloseHandle (WriteBufferEmptyEvent); if (WriteBufferFullEvent) CloseHandle (WriteBufferFullEvent); if (WriteThreadBuffer) TCfree (WriteThreadBuffer); SetLastError (sysErr); return FALSE; } static void StopFormatWriteThread () { if (WriteThreadRunning) { WaitForSingleObject (WriteBufferEmptyEvent, INFINITE); WriteThreadExitRequested = TRUE; SetEvent (WriteBufferFullEvent); WaitForSingleObject (WriteThreadHandle, INFINITE); } CloseHandle (WriteBufferEmptyEvent); CloseHandle (WriteBufferFullEvent); TCfree (WriteThreadBuffer); } BOOL FlushFormatWriteBuffer (void *dev, char *write_buf, int *write_buf_cnt, __int64 *nSecNo, PCRYPTO_INFO cryptoInfo) { UINT64_STRUCT unitNo; DWORD bytesWritten; if (*write_buf_cnt == 0) return TRUE; unitNo.Value = (*nSecNo * FormatSectorSize - *write_buf_cnt) / ENCRYPTION_DATA_UNIT_SIZE; EncryptDataUnits (write_buf, &unitNo, *write_buf_cnt / ENCRYPTION_DATA_UNIT_SIZE, cryptoInfo); if (WriteThreadRunning) { if (WaitForSingleObject (WriteBufferEmptyEvent, INFINITE) == WAIT_FAILED) return FALSE; if (WriteRequestResult != ERROR_SUCCESS) { SetEvent (WriteBufferEmptyEvent); SetLastError (WriteRequestResult); return FALSE; } memcpy (WriteThreadBuffer, write_buf, *write_buf_cnt); WriteRequestHandle = dev; WriteRequestSize = *write_buf_cnt; if (!SetEvent (WriteBufferFullEvent)) return FALSE; } else { if (!WriteFile ((HANDLE) dev, write_buf, *write_buf_cnt, &bytesWritten, NULL)) return FALSE; } *write_buf_cnt = 0; return TRUE; }