diff options
Diffstat (limited to 'src/Driver/Ntdriver.c')
-rw-r--r-- | src/Driver/Ntdriver.c | 1405 |
1 files changed, 1158 insertions, 247 deletions
diff --git a/src/Driver/Ntdriver.c b/src/Driver/Ntdriver.c index 73930404..b337ad86 100644 --- a/src/Driver/Ntdriver.c +++ b/src/Driver/Ntdriver.c @@ -13,6 +13,8 @@ #include "TCdefs.h" #include <ntddk.h> +#include <initguid.h> +#include <Ntddstor.h> #include "Crypto.h" #include "Fat.h" #include "Tests.h" @@ -30,6 +32,9 @@ #include "Cache.h" #include "Volumes.h" #include "VolumeFilter.h" +#include "cpu.h" +#include "rdrand.h" +#include "jitterentropy.h" #include <tchar.h> #include <initguid.h> @@ -69,6 +74,42 @@ #define IOCTL_VOLUME_IS_DYNAMIC CTL_CODE(IOCTL_VOLUME_BASE, 18, METHOD_BUFFERED, FILE_ANY_ACCESS) #endif +#ifndef StorageDeviceLBProvisioningProperty +#define StorageDeviceLBProvisioningProperty 11 +#endif + +#ifndef DeviceDsmAction_OffloadRead +#define DeviceDsmAction_OffloadRead ( 3 | DeviceDsmActionFlag_NonDestructive) +#endif + +#ifndef DeviceDsmAction_OffloadWrite +#define DeviceDsmAction_OffloadWrite 4 +#endif + +#ifndef DeviceDsmAction_Allocation +#define DeviceDsmAction_Allocation ( 5 | DeviceDsmActionFlag_NonDestructive) +#endif + +#ifndef DeviceDsmAction_Repair +#define DeviceDsmAction_Repair ( 6 | DeviceDsmActionFlag_NonDestructive) +#endif + +#ifndef DeviceDsmAction_Scrub +#define DeviceDsmAction_Scrub ( 7 | DeviceDsmActionFlag_NonDestructive) +#endif + +#ifndef DeviceDsmAction_DrtQuery +#define DeviceDsmAction_DrtQuery ( 8 | DeviceDsmActionFlag_NonDestructive) +#endif + +#ifndef DeviceDsmAction_DrtClear +#define DeviceDsmAction_DrtClear ( 9 | DeviceDsmActionFlag_NonDestructive) +#endif + +#ifndef DeviceDsmAction_DrtDisable +#define DeviceDsmAction_DrtDisable (10 | DeviceDsmActionFlag_NonDestructive) +#endif + /* Init section, which is thrown away as soon as DriverEntry returns */ #pragma alloc_text(INIT,DriverEntry) #pragma alloc_text(INIT,TCCreateRootDeviceObject) @@ -92,18 +133,166 @@ BOOL VolumeClassFilterRegistered = FALSE; BOOL CacheBootPassword = FALSE; BOOL CacheBootPim = FALSE; BOOL NonAdminSystemFavoritesAccessDisabled = FALSE; +BOOL BlockSystemTrimCommand = FALSE; +BOOL AllowWindowsDefrag = FALSE; +BOOL EraseKeysOnShutdown = TRUE; // by default, we erase encryption keys on system shutdown static size_t EncryptionThreadPoolFreeCpuCountLimit = 0; static BOOL SystemFavoriteVolumeDirty = FALSE; static BOOL PagingFileCreationPrevented = FALSE; static BOOL EnableExtendedIoctlSupport = FALSE; +static BOOL AllowTrimCommand = FALSE; +static BOOL RamEncryptionActivated = FALSE; static KeSaveExtendedProcessorStateFn KeSaveExtendedProcessorStatePtr = NULL; static KeRestoreExtendedProcessorStateFn KeRestoreExtendedProcessorStatePtr = NULL; +static ExGetFirmwareEnvironmentVariableFn ExGetFirmwareEnvironmentVariablePtr = NULL; +static KeQueryInterruptTimePreciseFn KeQueryInterruptTimePrecisePtr = NULL; +static KeAreAllApcsDisabledFn KeAreAllApcsDisabledPtr = NULL; +static KeSetSystemGroupAffinityThreadFn KeSetSystemGroupAffinityThreadPtr = NULL; +static KeQueryActiveGroupCountFn KeQueryActiveGroupCountPtr = NULL; +static KeQueryActiveProcessorCountExFn KeQueryActiveProcessorCountExPtr = NULL; +int EncryptionIoRequestCount = 0; +int EncryptionItemCount = 0; +int EncryptionFragmentSize = 0; POOL_TYPE ExDefaultNonPagedPoolType = NonPagedPool; ULONG ExDefaultMdlProtection = 0; PDEVICE_OBJECT VirtualVolumeDeviceObjects[MAX_MOUNTED_VOLUME_DRIVE_NUMBER + 1]; +BOOL AlignValue (ULONG ulValue, ULONG ulAlignment, ULONG *pulResult) +{ + BOOL bRet = FALSE; + HRESULT hr; + if (ulAlignment == 0) + { + *pulResult = ulValue; + bRet = TRUE; + } + else + { + ulAlignment -= 1; + hr = ULongAdd (ulValue, ulAlignment, &ulValue); + if (S_OK == hr) + { + *pulResult = ulValue & (~ulAlignment); + bRet = TRUE; + } + } + + return bRet; +} + +BOOL IsUefiBoot () +{ + BOOL bStatus = FALSE; + NTSTATUS ntStatus = STATUS_NOT_IMPLEMENTED; + + Dump ("IsUefiBoot BEGIN\n"); + ASSERT (KeGetCurrentIrql() == PASSIVE_LEVEL); + + if (ExGetFirmwareEnvironmentVariablePtr) + { + ULONG valueLengh = 0; + UNICODE_STRING emptyName; + GUID guid; + RtlInitUnicodeString(&emptyName, L""); + memset (&guid, 0, sizeof(guid)); + Dump ("IsUefiBoot calling ExGetFirmwareEnvironmentVariable\n"); + ntStatus = ExGetFirmwareEnvironmentVariablePtr (&emptyName, &guid, NULL, &valueLengh, NULL); + Dump ("IsUefiBoot ExGetFirmwareEnvironmentVariable returned 0x%08x\n", ntStatus); + } + else + { + Dump ("IsUefiBoot ExGetFirmwareEnvironmentVariable not found on the system\n"); + } + + if (STATUS_NOT_IMPLEMENTED != ntStatus) + bStatus = TRUE; + + Dump ("IsUefiBoot bStatus = %s END\n", bStatus? "TRUE" : "FALSE"); + return bStatus; +} + +void GetDriverRandomSeed (unsigned char* pbRandSeed, size_t cbRandSeed) +{ + LARGE_INTEGER iSeed, iSeed2; + byte digest[WHIRLPOOL_DIGESTSIZE]; + WHIRLPOOL_CTX tctx; + size_t count; + +#ifndef _WIN64 + KFLOATING_SAVE floatingPointState; + NTSTATUS saveStatus = STATUS_INVALID_PARAMETER; + if (HasISSE()) + saveStatus = KeSaveFloatingPointState (&floatingPointState); +#endif + + while (cbRandSeed) + { + WHIRLPOOL_init (&tctx); + // we hash current content of digest buffer which is uninitialized the first time + WHIRLPOOL_add (digest, WHIRLPOOL_DIGESTSIZE, &tctx); + + // we use various time information as source of entropy + KeQuerySystemTime( &iSeed ); + WHIRLPOOL_add ((unsigned char *) &(iSeed.QuadPart), sizeof(iSeed.QuadPart), &tctx); + iSeed = KeQueryPerformanceCounter (&iSeed2); + WHIRLPOOL_add ((unsigned char *) &(iSeed.QuadPart), sizeof(iSeed.QuadPart), &tctx); + WHIRLPOOL_add ((unsigned char *) &(iSeed2.QuadPart), sizeof(iSeed2.QuadPart), &tctx); + if (KeQueryInterruptTimePrecisePtr) + { + iSeed.QuadPart = KeQueryInterruptTimePrecisePtr (&iSeed2.QuadPart); + WHIRLPOOL_add ((unsigned char *) &(iSeed.QuadPart), sizeof(iSeed.QuadPart), &tctx); + WHIRLPOOL_add ((unsigned char *) &(iSeed2.QuadPart), sizeof(iSeed2.QuadPart), &tctx); + } + else + { + iSeed.QuadPart = KeQueryInterruptTime (); + WHIRLPOOL_add ((unsigned char *) &(iSeed.QuadPart), sizeof(iSeed.QuadPart), &tctx); + } + + /* use JitterEntropy library to get good quality random bytes based on CPU timing jitter */ + if (0 == jent_entropy_init ()) + { + struct rand_data *ec = jent_entropy_collector_alloc (1, 0); + if (ec) + { + ssize_t rndLen = jent_read_entropy (ec, (char*) digest, sizeof (digest)); + if (rndLen > 0) + WHIRLPOOL_add (digest, (unsigned int) rndLen, &tctx); + jent_entropy_collector_free (ec); + } + } + + // use RDSEED or RDRAND from CPU as source of entropy if enabled + if ( IsCpuRngEnabled() && + ( (HasRDSEED() && RDSEED_getBytes (digest, sizeof (digest))) + || (HasRDRAND() && RDRAND_getBytes (digest, sizeof (digest))) + )) + { + WHIRLPOOL_add (digest, sizeof(digest), &tctx); + } + WHIRLPOOL_finalize (&tctx, digest); + + count = VC_MIN (cbRandSeed, sizeof (digest)); + + // copy digest value to seed buffer + memcpy (pbRandSeed, digest, count); + cbRandSeed -= count; + pbRandSeed += count; + } + +#if !defined (_WIN64) + if (NT_SUCCESS (saveStatus)) + KeRestoreFloatingPointState (&floatingPointState); +#endif + + FAST_ERASE64 (digest, sizeof (digest)); + FAST_ERASE64 (&iSeed.QuadPart, 8); + FAST_ERASE64 (&iSeed2.QuadPart, 8); + burn (&tctx, sizeof(tctx)); +} + NTSTATUS DriverEntry (PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath) { @@ -111,7 +300,7 @@ NTSTATUS DriverEntry (PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath) LONG version; int i; - Dump ("DriverEntry " TC_APP_NAME " " VERSION_STRING "\n"); + Dump ("DriverEntry " TC_APP_NAME " " VERSION_STRING VERSION_STRING_SUFFIX "\n"); DetectX86Features (); @@ -126,14 +315,46 @@ NTSTATUS DriverEntry (PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath) ExDefaultMdlProtection = MdlMappingNoExecute; } + // KeAreAllApcsDisabled is available starting from Windows Server 2003 + if ((OsMajorVersion > 5) || (OsMajorVersion == 5 && OsMinorVersion >= 2)) + { + UNICODE_STRING KeAreAllApcsDisabledFuncName; + RtlInitUnicodeString(&KeAreAllApcsDisabledFuncName, L"KeAreAllApcsDisabled"); + + KeAreAllApcsDisabledPtr = (KeAreAllApcsDisabledFn) MmGetSystemRoutineAddress(&KeAreAllApcsDisabledFuncName); + } + // KeSaveExtendedProcessorState/KeRestoreExtendedProcessorState are available starting from Windows 7 + // KeQueryActiveGroupCount/KeQueryActiveProcessorCountEx/KeSetSystemGroupAffinityThread are available starting from Windows 7 if ((OsMajorVersion > 6) || (OsMajorVersion == 6 && OsMinorVersion >= 1)) { - UNICODE_STRING saveFuncName, restoreFuncName; + UNICODE_STRING saveFuncName, restoreFuncName, groupCountFuncName, procCountFuncName, setAffinityFuncName; RtlInitUnicodeString(&saveFuncName, L"KeSaveExtendedProcessorState"); RtlInitUnicodeString(&restoreFuncName, L"KeRestoreExtendedProcessorState"); + RtlInitUnicodeString(&groupCountFuncName, L"KeQueryActiveGroupCount"); + RtlInitUnicodeString(&procCountFuncName, L"KeQueryActiveProcessorCountEx"); + RtlInitUnicodeString(&setAffinityFuncName, L"KeSetSystemGroupAffinityThread"); KeSaveExtendedProcessorStatePtr = (KeSaveExtendedProcessorStateFn) MmGetSystemRoutineAddress(&saveFuncName); KeRestoreExtendedProcessorStatePtr = (KeRestoreExtendedProcessorStateFn) MmGetSystemRoutineAddress(&restoreFuncName); + KeSetSystemGroupAffinityThreadPtr = (KeSetSystemGroupAffinityThreadFn) MmGetSystemRoutineAddress(&setAffinityFuncName); + KeQueryActiveGroupCountPtr = (KeQueryActiveGroupCountFn) MmGetSystemRoutineAddress(&groupCountFuncName); + KeQueryActiveProcessorCountExPtr = (KeQueryActiveProcessorCountExFn) MmGetSystemRoutineAddress(&procCountFuncName); + } + + // ExGetFirmwareEnvironmentVariable is available starting from Windows 8 + if ((OsMajorVersion > 6) || (OsMajorVersion == 6 && OsMinorVersion >= 2)) + { + UNICODE_STRING funcName; + RtlInitUnicodeString(&funcName, L"ExGetFirmwareEnvironmentVariable"); + ExGetFirmwareEnvironmentVariablePtr = (ExGetFirmwareEnvironmentVariableFn) MmGetSystemRoutineAddress(&funcName); + } + + // KeQueryInterruptTimePrecise is available starting from Windows 8.1 + if ((OsMajorVersion > 6) || (OsMajorVersion == 6 && OsMinorVersion >= 3)) + { + UNICODE_STRING funcName; + RtlInitUnicodeString(&funcName, L"KeQueryInterruptTimePrecise"); + KeQueryInterruptTimePrecisePtr = (KeQueryInterruptTimePreciseFn) MmGetSystemRoutineAddress(&funcName); } // Load dump filter if the main driver is already loaded @@ -165,7 +386,7 @@ NTSTATUS DriverEntry (PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath) TC_BUG_CHECK (STATUS_INVALID_PARAMETER); } - LoadBootArguments(); + LoadBootArguments(IsUefiBoot ()); VolumeClassFilterRegistered = IsVolumeClassFilterRegistered(); DriverObject->DriverExtension->AddDevice = DriverAddDevice; @@ -174,6 +395,22 @@ NTSTATUS DriverEntry (PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath) TCfree (startKeyValue); } +#ifdef _WIN64 + if ((OsMajorVersion > 6) || (OsMajorVersion == 6 && OsMinorVersion >= 1)) + { + // we enable RAM encryption only starting from Windows 7 + if (RamEncryptionActivated) + { + if (t1ha_selfcheck__t1ha2() != 0) + TC_BUG_CHECK (STATUS_INVALID_PARAMETER); + if (!InitializeSecurityParameters(GetDriverRandomSeed)) + TC_BUG_CHECK (STATUS_INVALID_PARAMETER); + + EnableRamEncryption (TRUE); + } + } +#endif + for (i = 0; i <= IRP_MJ_MAXIMUM_FUNCTION; ++i) { DriverObject->MajorFunction[i] = TCDispatchQueueIRP; @@ -213,7 +450,7 @@ NTSTATUS DriverAddDevice (PDRIVER_OBJECT driverObject, PDEVICE_OBJECT pdo) return DriveFilterAddDevice (driverObject, pdo); } - +#if defined (DEBUG) || defined (DEBUG_TRACE) // Dumps a memory region to debug output void DumpMemory (void *mem, int size) { @@ -238,6 +475,7 @@ void DumpMemory (void *mem, int size) m+=8; } } +#endif BOOL IsAllZeroes (unsigned char* pbData, DWORD dwDataLen) { @@ -250,6 +488,54 @@ BOOL IsAllZeroes (unsigned char* pbData, DWORD dwDataLen) return TRUE; } +static wchar_t UpperCaseUnicodeChar (wchar_t c) +{ + if (c >= L'a' && c <= L'z') + return (c - L'a') + L'A'; + return c; +} + +static BOOL StringNoCaseCompare (const wchar_t* str1, const wchar_t* str2, size_t len) +{ + if (str1 && str2) + { + while (len) + { + if (UpperCaseUnicodeChar (*str1) != UpperCaseUnicodeChar (*str2)) + return FALSE; + str1++; + str2++; + len--; + } + } + + return TRUE; +} + +static BOOL CheckStringLength (const wchar_t* str, size_t cchSize, size_t minLength, size_t maxLength, size_t* pcchLength) +{ + size_t actualLength; + for (actualLength = 0; actualLength < cchSize; actualLength++) + { + if (str[actualLength] == 0) + break; + } + + if (pcchLength) + *pcchLength = actualLength; + + if (actualLength == cchSize) + return FALSE; + + if ((minLength != ((size_t) -1)) && (actualLength < minLength)) + return FALSE; + + if ((maxLength != ((size_t) -1)) && (actualLength > maxLength)) + return FALSE; + + return TRUE; +} + BOOL ValidateIOBufferSize (PIRP irp, size_t requiredBufferSize, ValidateIOBufferSizeType type) { PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (irp); @@ -710,6 +996,8 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION case IOCTL_DISK_GET_MEDIA_TYPES: case IOCTL_DISK_GET_DRIVE_GEOMETRY: + case IOCTL_STORAGE_GET_MEDIA_TYPES: + case IOCTL_DISK_UPDATE_DRIVE_SIZE: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_DISK_GET_DRIVE_GEOMETRY)\n"); /* Return the drive geometry for the disk. Note that we return values which were made up to suit the disk size. */ @@ -745,8 +1033,8 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION outputBuffer->Geometry.TracksPerCylinder = Extension->TracksPerCylinder; outputBuffer->Geometry.SectorsPerTrack = Extension->SectorsPerTrack; outputBuffer->Geometry.BytesPerSector = Extension->BytesPerSector; - /* add one sector to DiskLength since our partition size is DiskLength and its offset if BytesPerSector */ - outputBuffer->DiskSize.QuadPart = Extension->DiskLength + Extension->BytesPerSector; + // Add 1MB to the disk size to emulate the geometry of a real MBR disk + outputBuffer->DiskSize.QuadPart = Extension->DiskLength + BYTES_PER_MB; if (bFullBuffer) { @@ -774,25 +1062,6 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION } break; - case IOCTL_STORAGE_GET_MEDIA_TYPES: - Dump ("ProcessVolumeDeviceControlIrp (IOCTL_STORAGE_GET_MEDIA_TYPES)\n"); - /* Return the drive geometry for the disk. Note that we - return values which were made up to suit the disk size. */ - if (ValidateIOBufferSize (Irp, sizeof (DISK_GEOMETRY), ValidateOutput)) - { - PDISK_GEOMETRY outputBuffer = (PDISK_GEOMETRY) - Irp->AssociatedIrp.SystemBuffer; - - outputBuffer->MediaType = Extension->bRemovable ? RemovableMedia : FixedMedia; - outputBuffer->Cylinders.QuadPart = Extension->NumberOfCylinders; - outputBuffer->TracksPerCylinder = Extension->TracksPerCylinder; - outputBuffer->SectorsPerTrack = Extension->SectorsPerTrack; - outputBuffer->BytesPerSector = Extension->BytesPerSector; - Irp->IoStatus.Status = STATUS_SUCCESS; - Irp->IoStatus.Information = sizeof (DISK_GEOMETRY); - } - break; - case IOCTL_STORAGE_GET_MEDIA_TYPES_EX: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_STORAGE_GET_MEDIA_TYPES_EX)\n"); if (ValidateIOBufferSize (Irp, sizeof (GET_MEDIA_TYPES), ValidateOutput)) @@ -839,19 +1108,40 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Dump ("ProcessVolumeDeviceControlIrp (IOCTL_STORAGE_QUERY_PROPERTY)\n"); Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST; Irp->IoStatus.Information = 0; - if (EnableExtendedIoctlSupport) + if (EnableExtendedIoctlSupport || Extension->TrimEnabled) { if (ValidateIOBufferSize (Irp, sizeof (STORAGE_PROPERTY_QUERY), ValidateInput)) { PSTORAGE_PROPERTY_QUERY pStoragePropQuery = (PSTORAGE_PROPERTY_QUERY) Irp->AssociatedIrp.SystemBuffer; STORAGE_QUERY_TYPE type = pStoragePropQuery->QueryType; - Dump ("IOCTL_STORAGE_QUERY_PROPERTY - PropertyId = %d, type = %d\n", pStoragePropQuery->PropertyId, type); + Dump ("IOCTL_STORAGE_QUERY_PROPERTY - PropertyId = %d, type = %d, InputBufferLength = %d, OutputBufferLength = %d\n", pStoragePropQuery->PropertyId, type, (int) irpSp->Parameters.DeviceIoControl.InputBufferLength, (int) irpSp->Parameters.DeviceIoControl.OutputBufferLength); - /* return error if an unsupported type is encountered */ - Irp->IoStatus.Status = STATUS_NOT_SUPPORTED; - - if ( (pStoragePropQuery->PropertyId == StorageAccessAlignmentProperty) + if (Extension->bRawDevice && + (pStoragePropQuery->PropertyId == (STORAGE_PROPERTY_ID) StorageDeviceLBProvisioningProperty) + ) + { + IO_STATUS_BLOCK IoStatus; + Dump ("ProcessVolumeDeviceControlIrp: sending IOCTL_STORAGE_QUERY_PROPERTY (%d) to device\n", (int) pStoragePropQuery->PropertyId); + Irp->IoStatus.Status = ZwDeviceIoControlFile ( + Extension->hDeviceFile, + NULL, + NULL, + NULL, + &IoStatus, + IOCTL_STORAGE_QUERY_PROPERTY, + Irp->AssociatedIrp.SystemBuffer, + irpSp->Parameters.DeviceIoControl.InputBufferLength, + Irp->AssociatedIrp.SystemBuffer, + irpSp->Parameters.DeviceIoControl.OutputBufferLength); + Dump ("ProcessVolumeDeviceControlIrp: ZwDeviceIoControlFile returned 0x%.8X\n", (DWORD) Irp->IoStatus.Status); + if (Irp->IoStatus.Status == STATUS_SUCCESS) + { + Irp->IoStatus.Status = IoStatus.Status; + Irp->IoStatus.Information = IoStatus.Information; + } + } + else if ( (pStoragePropQuery->PropertyId == StorageAccessAlignmentProperty) || (pStoragePropQuery->PropertyId == StorageDeviceProperty) || (pStoragePropQuery->PropertyId == StorageAdapterProperty) || (pStoragePropQuery->PropertyId == StorageDeviceSeekPenaltyProperty) @@ -865,12 +1155,14 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION } else if (type == PropertyStandardQuery) { + ULONG descriptorSize; switch (pStoragePropQuery->PropertyId) { case StorageDeviceProperty: { + Dump ("IOCTL_STORAGE_QUERY_PROPERTY - StorageDeviceProperty\n"); /* Add 0x00 for NULL terminating string used as ProductId, ProductRevision, SerialNumber, VendorId */ - ULONG descriptorSize = sizeof (STORAGE_DEVICE_DESCRIPTOR) + 1; + descriptorSize = sizeof (STORAGE_DEVICE_DESCRIPTOR) + 1; if (ValidateIOBufferSize (Irp, descriptorSize, ValidateOutput)) { PSTORAGE_DEVICE_DESCRIPTOR outputBuffer = (PSTORAGE_DEVICE_DESCRIPTOR) Irp->AssociatedIrp.SystemBuffer; @@ -899,7 +1191,8 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION break; case StorageAdapterProperty: { - ULONG descriptorSize = sizeof (STORAGE_ADAPTER_DESCRIPTOR); + Dump ("IOCTL_STORAGE_QUERY_PROPERTY - StorageAdapterProperty\n"); + descriptorSize = sizeof (STORAGE_ADAPTER_DESCRIPTOR); if (ValidateIOBufferSize (Irp, descriptorSize, ValidateOutput)) { PSTORAGE_ADAPTER_DESCRIPTOR outputBuffer = (PSTORAGE_ADAPTER_DESCRIPTOR) Irp->AssociatedIrp.SystemBuffer; @@ -925,6 +1218,7 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION break; case StorageAccessAlignmentProperty: { + Dump ("IOCTL_STORAGE_QUERY_PROPERTY - StorageAccessAlignmentProperty\n"); if (ValidateIOBufferSize (Irp, sizeof (STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR), ValidateOutput)) { PSTORAGE_ACCESS_ALIGNMENT_DESCRIPTOR outputBuffer = (PSTORAGE_ACCESS_ALIGNMENT_DESCRIPTOR) Irp->AssociatedIrp.SystemBuffer; @@ -948,13 +1242,14 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION break; case StorageDeviceSeekPenaltyProperty: { + Dump ("IOCTL_STORAGE_QUERY_PROPERTY - StorageDeviceSeekPenaltyProperty\n"); if (ValidateIOBufferSize (Irp, sizeof (DEVICE_SEEK_PENALTY_DESCRIPTOR), ValidateOutput)) { PDEVICE_SEEK_PENALTY_DESCRIPTOR outputBuffer = (PDEVICE_SEEK_PENALTY_DESCRIPTOR) Irp->AssociatedIrp.SystemBuffer; - + Dump ("IOCTL_STORAGE_QUERY_PROPERTY - StorageDeviceSeekPenaltyProperty: set IncursSeekPenalty to %s\n", Extension->IncursSeekPenalty? "TRUE" : "FALSE"); outputBuffer->Version = sizeof(DEVICE_SEEK_PENALTY_DESCRIPTOR); outputBuffer->Size = sizeof(DEVICE_SEEK_PENALTY_DESCRIPTOR); - outputBuffer->IncursSeekPenalty = TRUE; //TODO: in case of SSD drive, we should probably return FALSE + outputBuffer->IncursSeekPenalty = (BOOLEAN) Extension->IncursSeekPenalty; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (DEVICE_SEEK_PENALTY_DESCRIPTOR); } @@ -970,13 +1265,14 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION break; case StorageDeviceTrimProperty: { + Dump ("IOCTL_STORAGE_QUERY_PROPERTY - StorageDeviceTrimProperty\n"); if (ValidateIOBufferSize (Irp, sizeof (DEVICE_TRIM_DESCRIPTOR), ValidateOutput)) { PDEVICE_TRIM_DESCRIPTOR outputBuffer = (PDEVICE_TRIM_DESCRIPTOR) Irp->AssociatedIrp.SystemBuffer; - + Dump ("IOCTL_STORAGE_QUERY_PROPERTY - StorageDeviceTrimProperty: set TrimEnabled to %s\n", Extension->TrimEnabled? "TRUE" : "FALSE"); outputBuffer->Version = sizeof(DEVICE_TRIM_DESCRIPTOR); outputBuffer->Size = sizeof(DEVICE_TRIM_DESCRIPTOR); - outputBuffer->TrimEnabled = FALSE; /* TODO: implement Trim support for SSD drives */ + outputBuffer->TrimEnabled = (BOOLEAN) Extension->TrimEnabled; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (DEVICE_TRIM_DESCRIPTOR); } @@ -993,8 +1289,8 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION } } } - } - } + } + } break; @@ -1009,7 +1305,7 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION outputBuffer->BootIndicator = FALSE; outputBuffer->RecognizedPartition = TRUE; outputBuffer->RewritePartition = FALSE; - outputBuffer->StartingOffset.QuadPart = Extension->BytesPerSector; + outputBuffer->StartingOffset.QuadPart = BYTES_PER_MB; // Set offset to 1MB to emulate the partition offset on a real MBR disk outputBuffer->PartitionLength.QuadPart= Extension->DiskLength; outputBuffer->PartitionNumber = 1; outputBuffer->HiddenSectors = 0; @@ -1026,7 +1322,7 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION outputBuffer->PartitionStyle = PARTITION_STYLE_MBR; outputBuffer->RewritePartition = FALSE; - outputBuffer->StartingOffset.QuadPart = Extension->BytesPerSector; + outputBuffer->StartingOffset.QuadPart = BYTES_PER_MB; // Set offset to 1MB to emulate the partition offset on a real MBR disk outputBuffer->PartitionLength.QuadPart= Extension->DiskLength; outputBuffer->PartitionNumber = 1; outputBuffer->Mbr.PartitionType = Extension->PartitionType; @@ -1054,7 +1350,7 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION outputBuffer->PartitionEntry->BootIndicator = FALSE; outputBuffer->PartitionEntry->RecognizedPartition = TRUE; outputBuffer->PartitionEntry->RewritePartition = FALSE; - outputBuffer->PartitionEntry->StartingOffset.QuadPart = Extension->BytesPerSector; + outputBuffer->PartitionEntry->StartingOffset.QuadPart = BYTES_PER_MB; // Set offset to 1MB to emulate the partition offset on a real MBR disk outputBuffer->PartitionEntry->PartitionLength.QuadPart = Extension->DiskLength; outputBuffer->PartitionEntry->PartitionNumber = 1; outputBuffer->PartitionEntry->HiddenSectors = 0; @@ -1090,7 +1386,7 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION outputBuffer->PartitionEntry->Mbr.BootIndicator = FALSE; outputBuffer->PartitionEntry->Mbr.RecognizedPartition = TRUE; outputBuffer->PartitionEntry->RewritePartition = FALSE; - outputBuffer->PartitionEntry->StartingOffset.QuadPart = Extension->BytesPerSector; + outputBuffer->PartitionEntry->StartingOffset.QuadPart = BYTES_PER_MB; // Set offset to 1MB to emulate the partition offset on a real MBR disk outputBuffer->PartitionEntry->PartitionLength.QuadPart = Extension->DiskLength; outputBuffer->PartitionEntry->PartitionNumber = 1; outputBuffer->PartitionEntry->Mbr.HiddenSectors = 0; @@ -1145,7 +1441,8 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION else { IO_STATUS_BLOCK ioStatus; - PVOID buffer = TCalloc (max (pVerifyInformation->Length, PAGE_SIZE)); + DWORD dwBuffersize = min (pVerifyInformation->Length, 16 * PAGE_SIZE); + PVOID buffer = TCalloc (dwBuffersize); if (!buffer) { @@ -1153,14 +1450,29 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION } else { - LARGE_INTEGER offset = pVerifyInformation->StartingOffset; + LARGE_INTEGER offset; + DWORD dwRemainingBytes = pVerifyInformation->Length, dwReadCount; offset.QuadPart = ullNewOffset; - Irp->IoStatus.Status = ZwReadFile (Extension->hDeviceFile, NULL, NULL, NULL, &ioStatus, buffer, pVerifyInformation->Length, &offset, NULL); - TCfree (buffer); + while (dwRemainingBytes) + { + dwReadCount = min (dwBuffersize, dwRemainingBytes); + Irp->IoStatus.Status = ZwReadFile (Extension->hDeviceFile, NULL, NULL, NULL, &ioStatus, buffer, dwReadCount, &offset, NULL); - if (NT_SUCCESS (Irp->IoStatus.Status) && ioStatus.Information != pVerifyInformation->Length) - Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + if (NT_SUCCESS (Irp->IoStatus.Status) && ioStatus.Information != dwReadCount) + { + Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + break; + } + else if (!NT_SUCCESS (Irp->IoStatus.Status)) + break; + + dwRemainingBytes -= dwReadCount; + offset.QuadPart += (ULONGLONG) dwReadCount; + } + + burn (buffer, dwBuffersize); + TCfree (buffer); } } @@ -1215,8 +1527,10 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION case IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS: Dump ("ProcessVolumeDeviceControlIrp (IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS)\n"); - // Vista's filesystem defragmenter fails if IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS does not succeed. - if (!(OsMajorVersion == 6 && OsMinorVersion == 0)) + // Vista's, Windows 8.1 and later filesystem defragmenter fails if IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS does not succeed. + if (!(OsMajorVersion == 6 && OsMinorVersion == 0) + && !(IsOSAtLeast (WIN_8_1) && AllowWindowsDefrag && Extension->bRawDevice) + ) { Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST; Irp->IoStatus.Information = 0; @@ -1224,10 +1538,24 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION else if (ValidateIOBufferSize (Irp, sizeof (VOLUME_DISK_EXTENTS), ValidateOutput)) { VOLUME_DISK_EXTENTS *extents = (VOLUME_DISK_EXTENTS *) Irp->AssociatedIrp.SystemBuffer; + - // No extent data can be returned as this is not a physical drive. - memset (extents, 0, sizeof (*extents)); - extents->NumberOfDiskExtents = 0; + if (IsOSAtLeast (WIN_8_1)) + { + // Windows 10 filesystem defragmenter works only if we report an extent with a real disk number + // So in the case of a VeraCrypt disk based volume, we use the disk number + // of the underlaying physical disk and we report a single extent + extents->NumberOfDiskExtents = 1; + extents->Extents[0].DiskNumber = Extension->DeviceNumber; + extents->Extents[0].StartingOffset.QuadPart = BYTES_PER_MB; // Set offset to 1MB to emulate the partition offset on a real MBR disk + extents->Extents[0].ExtentLength.QuadPart = Extension->DiskLength; + } + else + { + // Vista: No extent data can be returned as this is not a physical drive. + memset (extents, 0, sizeof (*extents)); + extents->NumberOfDiskExtents = 0; + } Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (*extents); @@ -1247,8 +1575,8 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION capacity->Version = sizeof (STORAGE_READ_CAPACITY); capacity->Size = sizeof (STORAGE_READ_CAPACITY); capacity->BlockLength = Extension->BytesPerSector; - capacity->NumberOfBlocks.QuadPart = (Extension->DiskLength / Extension->BytesPerSector) + 1; - capacity->DiskLength.QuadPart = Extension->DiskLength + Extension->BytesPerSector; + capacity->DiskLength.QuadPart = Extension->DiskLength + BYTES_PER_MB; // Add 1MB to the disk size to emulate the geometry of a real MBR disk + capacity->NumberOfBlocks.QuadPart = capacity->DiskLength.QuadPart / capacity->BlockLength; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (STORAGE_READ_CAPACITY); @@ -1361,6 +1689,21 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION break; + case IOCTL_DISK_UPDATE_PROPERTIES: + Dump ("ProcessVolumeDeviceControlIrp: returning STATUS_SUCCESS for IOCTL_DISK_UPDATE_PROPERTIES\n"); + Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Information = 0; + + break; + + case IOCTL_DISK_MEDIA_REMOVAL: + case IOCTL_STORAGE_MEDIA_REMOVAL: + Dump ("ProcessVolumeDeviceControlIrp: returning STATUS_SUCCESS for %ls\n", TCTranslateCode (irpSp->Parameters.DeviceIoControl.IoControlCode)); + Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Information = 0; + + break; + case IOCTL_DISK_GET_CLUSTER_INFO: Dump ("ProcessVolumeDeviceControlIrp: returning STATUS_NOT_SUPPORTED for %ls\n", TCTranslateCode (irpSp->Parameters.DeviceIoControl.IoControlCode)); Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST; @@ -1371,20 +1714,228 @@ NTSTATUS ProcessVolumeDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Irp->IoStatus.Information = 0; } break; + + case IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES: + Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES\n"); + Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST; + Irp->IoStatus.Information = 0; + if (Extension->bRawDevice && Extension->TrimEnabled) + { + if (ValidateIOBufferSize (Irp, sizeof (DEVICE_MANAGE_DATA_SET_ATTRIBUTES), ValidateInput)) + { + PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); + DWORD inputLength = irpSp->Parameters.DeviceIoControl.InputBufferLength; + PDEVICE_MANAGE_DATA_SET_ATTRIBUTES pInputAttrs = (PDEVICE_MANAGE_DATA_SET_ATTRIBUTES) Irp->AssociatedIrp.SystemBuffer; + DEVICE_DATA_MANAGEMENT_SET_ACTION action = pInputAttrs->Action; + BOOL bEntireSet = pInputAttrs->Flags & DEVICE_DSM_FLAG_ENTIRE_DATA_SET_RANGE? TRUE : FALSE; + ULONGLONG minSizedataSet = (ULONGLONG) pInputAttrs->DataSetRangesOffset + (ULONGLONG) pInputAttrs->DataSetRangesLength; + ULONGLONG minSizeParameter = (ULONGLONG) pInputAttrs->ParameterBlockOffset + (ULONGLONG) pInputAttrs->ParameterBlockLength; + ULONGLONG minSizeGeneric = sizeof(DEVICE_MANAGE_DATA_SET_ATTRIBUTES) + (ULONGLONG) pInputAttrs->ParameterBlockLength + (ULONGLONG) pInputAttrs->DataSetRangesLength; + PDEVICE_MANAGE_DATA_SET_ATTRIBUTES pNewSetAttrs = NULL; + ULONG ulNewInputLength = 0; + BOOL bForwardIoctl = FALSE; + + if (((ULONGLONG) inputLength) >= minSizeGeneric && ((ULONGLONG) inputLength) >= minSizedataSet && ((ULONGLONG) inputLength) >= minSizeParameter) + { + if (bEntireSet) + { + if (minSizedataSet) + { + Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DEVICE_DSM_FLAG_ENTIRE_DATA_SET_RANGE set but data set range specified=> Error.\n"); + Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + Irp->IoStatus.Information = 0; + } + else + { + DWORD dwDataSetOffset; + DWORD dwDataSetLength = sizeof(DEVICE_DATA_SET_RANGE); + + if (AlignValue (inputLength, sizeof(DEVICE_DATA_SET_RANGE), &dwDataSetOffset)) + { + Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DEVICE_DSM_FLAG_ENTIRE_DATA_SET_RANGE set. Setting data range to all volume.\n"); + + if (S_OK == ULongAdd(dwDataSetOffset, dwDataSetLength, &ulNewInputLength)) + { + pNewSetAttrs = (PDEVICE_MANAGE_DATA_SET_ATTRIBUTES) TCalloc (ulNewInputLength); + if (pNewSetAttrs) + { + PDEVICE_DATA_SET_RANGE pRange = (PDEVICE_DATA_SET_RANGE) (((unsigned char*) pNewSetAttrs) + dwDataSetOffset); + + memcpy (pNewSetAttrs, pInputAttrs, inputLength); + + pRange->StartingOffset = (ULONGLONG) Extension->cryptoInfo->hiddenVolume ? Extension->cryptoInfo->hiddenVolumeOffset : Extension->cryptoInfo->volDataAreaOffset; + pRange->LengthInBytes = Extension->DiskLength; + + pNewSetAttrs->Size = sizeof(DEVICE_MANAGE_DATA_SET_ATTRIBUTES); + pNewSetAttrs->Action = action; + pNewSetAttrs->Flags = pInputAttrs->Flags & (~DEVICE_DSM_FLAG_ENTIRE_DATA_SET_RANGE); + pNewSetAttrs->ParameterBlockOffset = pInputAttrs->ParameterBlockOffset; + pNewSetAttrs->ParameterBlockLength = pInputAttrs->ParameterBlockLength; + pNewSetAttrs->DataSetRangesOffset = dwDataSetOffset; + pNewSetAttrs->DataSetRangesLength = dwDataSetLength; + + bForwardIoctl = TRUE; + } + else + { + Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - Failed to allocate memory.\n"); + Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES; + Irp->IoStatus.Information = 0; + } + } + else + { + Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DEVICE_DSM_FLAG_ENTIRE_DATA_SET_RANGE set but data range length computation overflowed.\n"); + Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + Irp->IoStatus.Information = 0; + } + } + else + { + Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DEVICE_DSM_FLAG_ENTIRE_DATA_SET_RANGE set but data set offset computation overflowed.\n"); + Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + Irp->IoStatus.Information = 0; + } + } + } + else + { + Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - creating new data set range from input range.\n"); + ulNewInputLength = inputLength; + pNewSetAttrs = (PDEVICE_MANAGE_DATA_SET_ATTRIBUTES) TCalloc (inputLength); + if (pNewSetAttrs) + { + PDEVICE_DATA_SET_RANGE pNewRanges = (PDEVICE_DATA_SET_RANGE) (((unsigned char*) pNewSetAttrs) + pInputAttrs->DataSetRangesOffset); + PDEVICE_DATA_SET_RANGE pInputRanges = (PDEVICE_DATA_SET_RANGE) (((unsigned char*) pInputAttrs) + pInputAttrs->DataSetRangesOffset); + DWORD dwInputRangesCount = 0, dwNewRangesCount = 0, i; + ULONGLONG ullStartingOffset, ullNewOffset, ullEndOffset; + HRESULT hResult; + + memcpy (pNewSetAttrs, pInputAttrs, inputLength); + + dwInputRangesCount = pInputAttrs->DataSetRangesLength / sizeof(DEVICE_DATA_SET_RANGE); + + for (i = 0; i < dwInputRangesCount; i++) + { + ullStartingOffset = (ULONGLONG) pInputRanges[i].StartingOffset; + hResult = ULongLongAdd(ullStartingOffset, + (ULONGLONG) Extension->cryptoInfo->hiddenVolume ? Extension->cryptoInfo->hiddenVolumeOffset : Extension->cryptoInfo->volDataAreaOffset, + &ullNewOffset); + if (hResult != S_OK) + continue; + else if (S_OK != ULongLongAdd(ullStartingOffset, (ULONGLONG) pInputRanges[i].LengthInBytes, &ullEndOffset)) + continue; + else if (ullEndOffset > (ULONGLONG) Extension->DiskLength) + continue; + else if (ullNewOffset > 0) + { + pNewRanges[dwNewRangesCount].StartingOffset = (LONGLONG) ullNewOffset; + pNewRanges[dwNewRangesCount].LengthInBytes = pInputRanges[i].LengthInBytes; + + dwNewRangesCount++; + } + } + + Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - %d valid range processed from %d range in input.\n", (int) dwNewRangesCount, (int) dwInputRangesCount); + + pNewSetAttrs->DataSetRangesLength = dwNewRangesCount * sizeof (DEVICE_DATA_SET_RANGE); + + bForwardIoctl = TRUE; + } + else + { + Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - Failed to allocate memory.\n"); + Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES; + Irp->IoStatus.Information = 0; + } + } + } + else + { + Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - buffer containing DEVICE_MANAGE_DATA_SET_ATTRIBUTES has invalid length.\n"); + Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + Irp->IoStatus.Information = 0; + } + + + if (bForwardIoctl) + { + if (action == DeviceDsmAction_Trim) + { + Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_Trim.\n"); + + if (Extension->cryptoInfo->hiddenVolume || !AllowTrimCommand) + { + Dump ("ProcessVolumeDeviceControlIrp: TRIM command filtered\n"); + Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Information = 0; + } + else + { + IO_STATUS_BLOCK IoStatus; + Dump ("ProcessVolumeDeviceControlIrp: sending TRIM to device\n"); + Irp->IoStatus.Status = ZwDeviceIoControlFile ( + Extension->hDeviceFile, + NULL, + NULL, + NULL, + &IoStatus, + IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES, + (PVOID) pNewSetAttrs, + ulNewInputLength, + NULL, + 0); + Dump ("ProcessVolumeDeviceControlIrp: ZwDeviceIoControlFile returned 0x%.8X\n", (DWORD) Irp->IoStatus.Status); + if (Irp->IoStatus.Status == STATUS_SUCCESS) + { + Irp->IoStatus.Status = IoStatus.Status; + Irp->IoStatus.Information = IoStatus.Information; + } + else + Irp->IoStatus.Information = 0; + } + } + else + { + switch (action) + { + case DeviceDsmAction_Notification: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_Notification\n"); break; + case DeviceDsmAction_OffloadRead: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_OffloadRead\n"); break; + case DeviceDsmAction_OffloadWrite: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_OffloadWrite\n"); break; + case DeviceDsmAction_Allocation: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_Allocation\n"); break; + case DeviceDsmAction_Scrub: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_Scrub\n"); break; + case DeviceDsmAction_DrtQuery: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_DrtQuery\n"); break; + case DeviceDsmAction_DrtClear: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_DrtClear\n"); break; + case DeviceDsmAction_DrtDisable: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - DeviceDsmAction_DrtDisable\n"); break; + default: Dump ("ProcessVolumeDeviceControlIrp: IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES - unknown action %d\n", (int) action); break; + } + + } + } + + if (pNewSetAttrs) + TCfree (pNewSetAttrs); + } + } +#if defined (DEBUG) || defined (DEBUG_TRACE) + else + Dump ("ProcessVolumeDeviceControlIrp: returning STATUS_INVALID_DEVICE_REQUEST for IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES\n"); +#endif + break; case IOCTL_STORAGE_CHECK_PRIORITY_HINT_SUPPORT: - case IOCTL_DISK_MEDIA_REMOVAL: case IOCTL_VOLUME_QUERY_ALLOCATION_HINT: case FT_BALANCED_READ_MODE: case IOCTL_STORAGE_GET_DEVICE_NUMBER: + case IOCTL_MOUNTDEV_LINK_CREATED: Dump ("ProcessVolumeDeviceControlIrp: returning STATUS_INVALID_DEVICE_REQUEST for %ls\n", TCTranslateCode (irpSp->Parameters.DeviceIoControl.IoControlCode)); Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST; Irp->IoStatus.Information = 0; break; default: - Dump ("ProcessVolumeDeviceControlIrp (unknown code 0x%.8X)\n", irpSp->Parameters.DeviceIoControl.IoControlCode); - return TCCompleteIrp (Irp, STATUS_INVALID_DEVICE_REQUEST, 0); - } + Dump ("ProcessVolumeDeviceControlIrp (unknown code 0x%.8X)\n", irpSp->Parameters.DeviceIoControl.IoControlCode); + return TCCompleteIrp (Irp, STATUS_INVALID_DEVICE_REQUEST, 0); + } #if defined(DEBUG) || defined (DEBG_TRACE) if (!NT_SUCCESS (Irp->IoStatus.Status)) @@ -1408,7 +1959,7 @@ NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Ex switch (irpSp->Parameters.DeviceIoControl.IoControlCode) { case TC_IOCTL_GET_DRIVER_VERSION: - case TC_IOCTL_LEGACY_GET_DRIVER_VERSION: + if (ValidateIOBufferSize (Irp, sizeof (LONG), ValidateOutput)) { LONG tmp = VERSION_NUM; @@ -1474,10 +2025,30 @@ NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Ex IO_STATUS_BLOCK IoStatus; LARGE_INTEGER offset; ACCESS_MASK access = FILE_READ_ATTRIBUTES; + PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); if (!ValidateIOBufferSize (Irp, sizeof (OPEN_TEST_STRUCT), ValidateInputOutput)) break; + if (irpSp->Parameters.DeviceIoControl.InputBufferLength != sizeof (OPEN_TEST_STRUCT)) + { + Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + Irp->IoStatus.Information = 0; + break; + } + + // check that opentest->wszFileName is a device path that starts with "\\Device\\Harddisk" + // 16 is the length of "\\Device\\Harddisk" which is the minimum + if ( !CheckStringLength (opentest->wszFileName, TC_MAX_PATH, 16, (size_t) -1, NULL) + || (!StringNoCaseCompare (opentest->wszFileName, L"\\Device\\Harddisk", 16)) + ) + { + Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + Irp->IoStatus.Information = 0; + break; + } + + EnsureNullTerminatedString (opentest->wszFileName, sizeof (opentest->wszFileName)); RtlInitUnicodeString (&FullFileName, opentest->wszFileName); @@ -1595,7 +2166,7 @@ NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Ex &offset, NULL); - if (NT_SUCCESS (ntStatus)) + if (NT_SUCCESS (ntStatus) && (IoStatus.Information >= TC_VOLUME_HEADER_EFFECTIVE_SIZE)) { /* compute the ID of this volume: SHA-256 of the effective header */ sha256 (opentest->volumeIDs[volumeType], readBuffer, TC_VOLUME_HEADER_EFFECTIVE_SIZE); @@ -1631,11 +2202,26 @@ NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Ex UNICODE_STRING FullFileName; IO_STATUS_BLOCK IoStatus; LARGE_INTEGER offset; - byte readBuffer [TC_SECTOR_SIZE_BIOS]; + size_t devicePathLen = 0; + WCHAR* wszPath = NULL; if (!ValidateIOBufferSize (Irp, sizeof (GetSystemDriveConfigurationRequest), ValidateInputOutput)) break; + // check that request->DevicePath has the expected format "\\Device\\HarddiskXXX\\Partition0" + // 28 is the length of "\\Device\\Harddisk0\\Partition0" which is the minimum + // 30 is the length of "\\Device\\Harddisk255\\Partition0" which is the maximum + wszPath = request->DevicePath; + if ( !CheckStringLength (wszPath, TC_MAX_PATH, 28, 30, &devicePathLen) + || (memcmp (wszPath, L"\\Device\\Harddisk", 16 * sizeof (WCHAR))) + || (memcmp (wszPath + (devicePathLen - 11), L"\\Partition0", 11 * sizeof (WCHAR))) + ) + { + Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + Irp->IoStatus.Information = 0; + break; + } + EnsureNullTerminatedString (request->DevicePath, sizeof (request->DevicePath)); RtlInitUnicodeString (&FullFileName, request->DevicePath); @@ -1647,68 +2233,88 @@ NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Ex if (NT_SUCCESS (ntStatus)) { - // Determine if the first sector contains a portion of the VeraCrypt Boot Loader - offset.QuadPart = 0; // MBR - - ntStatus = ZwReadFile (NtFileHandle, - NULL, - NULL, - NULL, - &IoStatus, - readBuffer, - sizeof(readBuffer), - &offset, - NULL); - - if (NT_SUCCESS (ntStatus)) + byte *readBuffer = TCalloc (TC_MAX_VOLUME_SECTOR_SIZE); + if (!readBuffer) { - size_t i; - - // Check for dynamic drive - request->DriveIsDynamic = FALSE; + Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES; + Irp->IoStatus.Information = 0; + } + else + { + // Determine if the first sector contains a portion of the VeraCrypt Boot Loader + offset.QuadPart = 0; // MBR + + ntStatus = ZwReadFile (NtFileHandle, + NULL, + NULL, + NULL, + &IoStatus, + readBuffer, + TC_MAX_VOLUME_SECTOR_SIZE, + &offset, + NULL); - if (readBuffer[510] == 0x55 && readBuffer[511] == 0xaa) + if (NT_SUCCESS (ntStatus)) { - int i; - for (i = 0; i < 4; ++i) + // check that we could read all needed data + if (IoStatus.Information >= TC_SECTOR_SIZE_BIOS) { - if (readBuffer[446 + i * 16 + 4] == PARTITION_LDM) + size_t i; + + // Check for dynamic drive + request->DriveIsDynamic = FALSE; + + if (readBuffer[510] == 0x55 && readBuffer[511] == 0xaa) { - request->DriveIsDynamic = TRUE; - break; + int i; + for (i = 0; i < 4; ++i) + { + if (readBuffer[446 + i * 16 + 4] == PARTITION_LDM) + { + request->DriveIsDynamic = TRUE; + break; + } + } } - } - } - request->BootLoaderVersion = 0; - request->Configuration = 0; - request->UserConfiguration = 0; - request->CustomUserMessage[0] = 0; + request->BootLoaderVersion = 0; + request->Configuration = 0; + request->UserConfiguration = 0; + request->CustomUserMessage[0] = 0; - // Search for the string "VeraCrypt" - for (i = 0; i < sizeof (readBuffer) - strlen (TC_APP_NAME); ++i) - { - if (memcmp (readBuffer + i, TC_APP_NAME, strlen (TC_APP_NAME)) == 0) - { - request->BootLoaderVersion = BE16 (*(uint16 *) (readBuffer + TC_BOOT_SECTOR_VERSION_OFFSET)); - request->Configuration = readBuffer[TC_BOOT_SECTOR_CONFIG_OFFSET]; - - if (request->BootLoaderVersion != 0 && request->BootLoaderVersion <= VERSION_NUM) + // Search for the string "VeraCrypt" + for (i = 0; i < TC_SECTOR_SIZE_BIOS - strlen (TC_APP_NAME); ++i) { - request->UserConfiguration = readBuffer[TC_BOOT_SECTOR_USER_CONFIG_OFFSET]; - memcpy (request->CustomUserMessage, readBuffer + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET, TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH); + if (memcmp (readBuffer + i, TC_APP_NAME, strlen (TC_APP_NAME)) == 0) + { + request->BootLoaderVersion = BE16 (*(uint16 *) (readBuffer + TC_BOOT_SECTOR_VERSION_OFFSET)); + request->Configuration = readBuffer[TC_BOOT_SECTOR_CONFIG_OFFSET]; + + if (request->BootLoaderVersion != 0 && request->BootLoaderVersion <= VERSION_NUM) + { + request->UserConfiguration = readBuffer[TC_BOOT_SECTOR_USER_CONFIG_OFFSET]; + memcpy (request->CustomUserMessage, readBuffer + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET, TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH); + } + break; + } } - break; + + Irp->IoStatus.Status = STATUS_SUCCESS; + Irp->IoStatus.Information = sizeof (*request); + } + else + { + Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + Irp->IoStatus.Information = 0; } } + else + { + Irp->IoStatus.Status = ntStatus; + Irp->IoStatus.Information = 0; + } - Irp->IoStatus.Status = STATUS_SUCCESS; - Irp->IoStatus.Information = sizeof (*request); - } - else - { - Irp->IoStatus.Status = ntStatus; - Irp->IoStatus.Information = 0; + TCfree (readBuffer); } ZwClose (NtFileHandle); @@ -1787,7 +2393,6 @@ NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Ex list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_OUTER; // Normal/outer volume (hidden volume protected) else list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_NORMAL; // Normal volume - list->truecryptMode[ListExtension->nDosDriveNo] = ListExtension->cryptoInfo->bTrueCryptMode; } } @@ -1796,21 +2401,6 @@ NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Ex } break; - case TC_IOCTL_LEGACY_GET_MOUNTED_VOLUMES: - if (ValidateIOBufferSize (Irp, sizeof (uint32), ValidateOutput)) - { - // Prevent the user from downgrading to versions lower than 5.0 by faking mounted volumes. - // The user could render the system unbootable by downgrading when boot encryption - // is active or being set up. - - memset (Irp->AssociatedIrp.SystemBuffer, 0, irpSp->Parameters.DeviceIoControl.OutputBufferLength); - *(uint32 *) Irp->AssociatedIrp.SystemBuffer = 0xffffFFFF; - - Irp->IoStatus.Status = STATUS_SUCCESS; - Irp->IoStatus.Information = irpSp->Parameters.DeviceIoControl.OutputBufferLength; - } - break; - case TC_IOCTL_GET_VOLUME_PROPERTIES: if (ValidateIOBufferSize (Irp, sizeof (VOLUME_PROPERTIES_STRUCT), ValidateInputOutput)) { @@ -1843,6 +2433,7 @@ NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Ex prop->volumeHeaderFlags = ListExtension->cryptoInfo->HeaderFlags; prop->readOnly = ListExtension->bReadOnly; prop->removable = ListExtension->bRemovable; + prop->mountDisabled = ListExtension->bMountManager? FALSE : TRUE; prop->partitionInInactiveSysEncScope = ListExtension->PartitionInInactiveSysEncScope; prop->hiddenVolume = ListExtension->cryptoInfo->hiddenVolume; @@ -2078,12 +2669,13 @@ NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Ex if (ValidateIOBufferSize (Irp, sizeof (MOUNT_STRUCT), ValidateInputOutput)) { MOUNT_STRUCT *mount = (MOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer; + PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); - if (mount->VolumePassword.Length > MAX_PASSWORD || mount->ProtectedHidVolPassword.Length > MAX_PASSWORD + if ((irpSp->Parameters.DeviceIoControl.InputBufferLength != sizeof (MOUNT_STRUCT)) + || mount->VolumePassword.Length > MAX_PASSWORD || mount->ProtectedHidVolPassword.Length > MAX_PASSWORD || mount->pkcs5_prf < 0 || mount->pkcs5_prf > LAST_PRF_ID || mount->VolumePim < -1 || mount->VolumePim == INT_MAX || mount->ProtectedHidVolPkcs5Prf < 0 || mount->ProtectedHidVolPkcs5Prf > LAST_PRF_ID - || (mount->bTrueCryptMode != FALSE && mount->bTrueCryptMode != TRUE) ) { Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; @@ -2101,7 +2693,6 @@ NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Ex burn (&mount->ProtectedHidVolPassword, sizeof (mount->ProtectedHidVolPassword)); burn (&mount->pkcs5_prf, sizeof (mount->pkcs5_prf)); burn (&mount->VolumePim, sizeof (mount->VolumePim)); - burn (&mount->bTrueCryptMode, sizeof (mount->bTrueCryptMode)); burn (&mount->ProtectedHidVolPkcs5Prf, sizeof (mount->ProtectedHidVolPkcs5Prf)); burn (&mount->ProtectedHidVolPim, sizeof (mount->ProtectedHidVolPim)); } @@ -2112,6 +2703,14 @@ NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Ex { UNMOUNT_STRUCT *unmount = (UNMOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer; PDEVICE_OBJECT ListDevice = GetVirtualVolumeDeviceObject (unmount->nDosDriveNo); + PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); + + if (irpSp->Parameters.DeviceIoControl.InputBufferLength != sizeof (UNMOUNT_STRUCT)) + { + Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + Irp->IoStatus.Information = 0; + break; + } unmount->nReturnCode = ERR_DRIVE_NOT_FOUND; @@ -2132,6 +2731,14 @@ NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Ex if (ValidateIOBufferSize (Irp, sizeof (UNMOUNT_STRUCT), ValidateInputOutput)) { UNMOUNT_STRUCT *unmount = (UNMOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer; + PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); + + if (irpSp->Parameters.DeviceIoControl.InputBufferLength != sizeof (UNMOUNT_STRUCT)) + { + Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; + Irp->IoStatus.Information = 0; + break; + } unmount->nReturnCode = UnmountAllDevices (unmount, unmount->ignoreOpenFiles); @@ -2140,6 +2747,11 @@ NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Ex } break; + case VC_IOCTL_EMERGENCY_CLEAR_ALL_KEYS: + EmergencyClearAllKeys (Irp, irpSp); + WipeCache(); + break; + case TC_IOCTL_BOOT_ENCRYPTION_SETUP: Irp->IoStatus.Status = StartBootEncryptionSetup (DeviceObject, Irp, irpSp); Irp->IoStatus.Information = 0; @@ -2266,6 +2878,27 @@ NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Ex } break; + case VC_IOCTL_IS_RAM_ENCRYPTION_ENABLED: + if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput)) + { + *(int *) Irp->AssociatedIrp.SystemBuffer = IsRamEncryptionEnabled() ? 1 : 0; + Irp->IoStatus.Information = sizeof (int); + Irp->IoStatus.Status = STATUS_SUCCESS; + } + break; + + case VC_IOCTL_ENCRYPTION_QUEUE_PARAMS: + if (ValidateIOBufferSize (Irp, sizeof (EncryptionQueueParameters), ValidateOutput)) + { + EncryptionQueueParameters* pParams = (EncryptionQueueParameters*) Irp->AssociatedIrp.SystemBuffer; + pParams->EncryptionFragmentSize = EncryptionFragmentSize; + pParams->EncryptionIoRequestCount = EncryptionIoRequestCount; + pParams->EncryptionItemCount = EncryptionItemCount; + Irp->IoStatus.Information = sizeof (EncryptionQueueParameters); + Irp->IoStatus.Status = STATUS_SUCCESS; + } + break; + default: return TCCompleteIrp (Irp, STATUS_INVALID_DEVICE_REQUEST, 0); } @@ -2541,6 +3174,21 @@ VOID VolumeThreadProc (PVOID Context) Extension->Queue.HostFileHandle = Extension->hDeviceFile; Extension->Queue.VirtualDeviceLength = Extension->DiskLength; Extension->Queue.MaxReadAheadOffset.QuadPart = Extension->HostLength; + if (bDevice && pThreadBlock->mount->bPartitionInInactiveSysEncScope + && (!Extension->cryptoInfo->hiddenVolume) + && (Extension->cryptoInfo->EncryptedAreaLength.Value != Extension->cryptoInfo->VolumeSize.Value) + ) + { + // Support partial encryption only in the case of system encryption + Extension->Queue.EncryptedAreaStart = 0; + Extension->Queue.EncryptedAreaEnd = Extension->cryptoInfo->EncryptedAreaLength.Value - 1; + if (Extension->Queue.CryptoInfo->EncryptedAreaLength.Value == 0) + { + Extension->Queue.EncryptedAreaStart = -1; + Extension->Queue.EncryptedAreaEnd = -1; + } + Extension->Queue.bSupportPartialEncryption = TRUE; + } if (Extension->SecurityClientContextValid) Extension->Queue.SecurityClientContext = &Extension->SecurityClientContext; @@ -2674,6 +3322,9 @@ LPWSTR TCTranslateCode (ULONG ulCode) TC_CASE_RET_NAME (TC_IOCTL_WIPE_PASSWORD_CACHE); TC_CASE_RET_NAME (TC_IOCTL_WRITE_BOOT_DRIVE_SECTOR); TC_CASE_RET_NAME (VC_IOCTL_GET_DRIVE_GEOMETRY_EX); + TC_CASE_RET_NAME (VC_IOCTL_EMERGENCY_CLEAR_ALL_KEYS); + TC_CASE_RET_NAME (VC_IOCTL_IS_RAM_ENCRYPTION_ENABLED); + TC_CASE_RET_NAME (VC_IOCTL_ENCRYPTION_QUEUE_PARAMS); TC_CASE_RET_NAME (IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS); @@ -2772,6 +3423,8 @@ LPWSTR TCTranslateCode (ULONG ulCode) return (LPWSTR) _T ("IOCTL_DISK_GET_MEDIA_TYPES"); else if (ulCode == IOCTL_DISK_IS_CLUSTERED) return (LPWSTR) _T ("IOCTL_DISK_IS_CLUSTERED"); + else if (ulCode == IOCTL_DISK_UPDATE_DRIVE_SIZE) + return (LPWSTR) _T ("IOCTL_DISK_UPDATE_DRIVE_SIZE"); else if (ulCode == IOCTL_STORAGE_GET_MEDIA_TYPES) return (LPWSTR) _T ("IOCTL_STORAGE_GET_MEDIA_TYPES"); else if (ulCode == IOCTL_STORAGE_GET_HOTPLUG_INFO) @@ -2798,6 +3451,10 @@ LPWSTR TCTranslateCode (ULONG ulCode) return (LPWSTR) _T ("IOCTL_VOLUME_POST_ONLINE"); else if (ulCode == IOCTL_STORAGE_CHECK_PRIORITY_HINT_SUPPORT) return (LPWSTR) _T ("IOCTL_STORAGE_CHECK_PRIORITY_HINT_SUPPORT"); + else if (ulCode == IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES) + return (LPWSTR) _T ("IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES"); + else if (ulCode == IOCTL_DISK_GROW_PARTITION) + return (LPWSTR) _T ("IOCTL_DISK_GROW_PARTITION"); else if (ulCode == IRP_MJ_READ) return (LPWSTR) _T ("IRP_MJ_READ"); else if (ulCode == IRP_MJ_WRITE) @@ -2848,31 +3505,21 @@ void TCDeleteDeviceObject (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension) if (Extension->SecurityClientContextValid) { - if (OsMajorVersion == 5 && OsMinorVersion == 0) - { - ObDereferenceObject (Extension->SecurityClientContext.ClientToken); - } - else - { - // Windows 2000 does not support PsDereferenceImpersonationToken() used by SeDeleteClientSecurity(). - // TODO: Use only SeDeleteClientSecurity() once support for Windows 2000 is dropped. - - VOID (*PsDereferenceImpersonationTokenD) (PACCESS_TOKEN ImpersonationToken); - UNICODE_STRING name; - RtlInitUnicodeString (&name, L"PsDereferenceImpersonationToken"); + VOID (*PsDereferenceImpersonationTokenD) (PACCESS_TOKEN ImpersonationToken); + UNICODE_STRING name; + RtlInitUnicodeString (&name, L"PsDereferenceImpersonationToken"); - PsDereferenceImpersonationTokenD = MmGetSystemRoutineAddress (&name); - if (!PsDereferenceImpersonationTokenD) - TC_BUG_CHECK (STATUS_NOT_IMPLEMENTED); + PsDereferenceImpersonationTokenD = MmGetSystemRoutineAddress (&name); + if (!PsDereferenceImpersonationTokenD) + TC_BUG_CHECK (STATUS_NOT_IMPLEMENTED); -# define PsDereferencePrimaryToken -# define PsDereferenceImpersonationToken PsDereferenceImpersonationTokenD +# define PsDereferencePrimaryToken +# define PsDereferenceImpersonationToken PsDereferenceImpersonationTokenD - SeDeleteClientSecurity (&Extension->SecurityClientContext); + SeDeleteClientSecurity (&Extension->SecurityClientContext); -# undef PsDereferencePrimaryToken -# undef PsDereferenceImpersonationToken - } +# undef PsDereferencePrimaryToken +# undef PsDereferenceImpersonationToken } VirtualVolumeDeviceObjects[Extension->nDosDriveNo] = NULL; @@ -2912,6 +3559,18 @@ void OnShutdownPending () while (SendDeviceIoControlRequest (RootDeviceObject, TC_IOCTL_WIPE_PASSWORD_CACHE, NULL, 0, NULL, 0) == STATUS_INSUFFICIENT_RESOURCES); } +typedef struct +{ + PWSTR deviceName; ULONG IoControlCode; void *InputBuffer; ULONG InputBufferSize; void *OutputBuffer; ULONG OutputBufferSize; + NTSTATUS Status; + KEVENT WorkItemCompletedEvent; +} TCDeviceIoControlWorkItemArgs; + +static VOID TCDeviceIoControlWorkItemRoutine (PDEVICE_OBJECT rootDeviceObject, TCDeviceIoControlWorkItemArgs *arg) +{ + arg->Status = TCDeviceIoControl (arg->deviceName, arg->IoControlCode, arg->InputBuffer, arg->InputBufferSize, arg->OutputBuffer, arg->OutputBufferSize); + KeSetEvent (&arg->WorkItemCompletedEvent, IO_NO_INCREMENT, FALSE); +} NTSTATUS TCDeviceIoControl (PWSTR deviceName, ULONG IoControlCode, void *InputBuffer, ULONG InputBufferSize, void *OutputBuffer, ULONG OutputBufferSize) { @@ -2923,6 +3582,30 @@ NTSTATUS TCDeviceIoControl (PWSTR deviceName, ULONG IoControlCode, void *InputBu KEVENT event; UNICODE_STRING name; + if ((KeGetCurrentIrql() >= APC_LEVEL) || VC_KeAreAllApcsDisabled()) + { + TCDeviceIoControlWorkItemArgs args; + + PIO_WORKITEM workItem = IoAllocateWorkItem (RootDeviceObject); + if (!workItem) + return STATUS_INSUFFICIENT_RESOURCES; + + args.deviceName = deviceName; + args.IoControlCode = IoControlCode; + args.InputBuffer = InputBuffer; + args.InputBufferSize = InputBufferSize; + args.OutputBuffer = OutputBuffer; + args.OutputBufferSize = OutputBufferSize; + + KeInitializeEvent (&args.WorkItemCompletedEvent, SynchronizationEvent, FALSE); + IoQueueWorkItem (workItem, TCDeviceIoControlWorkItemRoutine, DelayedWorkQueue, &args); + + KeWaitForSingleObject (&args.WorkItemCompletedEvent, Executive, KernelMode, FALSE, NULL); + IoFreeWorkItem (workItem); + + return args.Status; + } + RtlInitUnicodeString(&name, deviceName); ntStatus = IoGetDeviceObjectPointer (&name, FILE_READ_ATTRIBUTES, &fileObject, &deviceObject); @@ -2983,7 +3666,7 @@ NTSTATUS SendDeviceIoControlRequest (PDEVICE_OBJECT deviceObject, ULONG ioContro PIRP irp; KEVENT event; - if (KeGetCurrentIrql() > APC_LEVEL) + if ((KeGetCurrentIrql() >= APC_LEVEL) || VC_KeAreAllApcsDisabled()) { SendDeviceIoControlRequestWorkItemArgs args; @@ -3036,11 +3719,16 @@ NTSTATUS ProbeRealDriveSize (PDEVICE_OBJECT driveDeviceObject, LARGE_INTEGER *dr LARGE_INTEGER offset; byte *sectorBuffer; ULONGLONG startTime; + ULONG sectorSize; if (!UserCanAccessDriveDevice()) return STATUS_ACCESS_DENIED; - sectorBuffer = TCalloc (TC_SECTOR_SIZE_BIOS); + status = GetDeviceSectorSize (driveDeviceObject, §orSize); + if (!NT_SUCCESS (status)) + return status; + + sectorBuffer = TCalloc (sectorSize); if (!sectorBuffer) return STATUS_INSUFFICIENT_RESOURCES; @@ -3055,12 +3743,12 @@ NTSTATUS ProbeRealDriveSize (PDEVICE_OBJECT driveDeviceObject, LARGE_INTEGER *dr } startTime = KeQueryInterruptTime (); - for (offset.QuadPart = sysLength.QuadPart; ; offset.QuadPart += TC_SECTOR_SIZE_BIOS) + for (offset.QuadPart = sysLength.QuadPart; ; offset.QuadPart += sectorSize) { - status = TCReadDevice (driveDeviceObject, sectorBuffer, offset, TC_SECTOR_SIZE_BIOS); + status = TCReadDevice (driveDeviceObject, sectorBuffer, offset, sectorSize); if (NT_SUCCESS (status)) - status = TCWriteDevice (driveDeviceObject, sectorBuffer, offset, TC_SECTOR_SIZE_BIOS); + status = TCWriteDevice (driveDeviceObject, sectorBuffer, offset, sectorSize); if (!NT_SUCCESS (status)) { @@ -3299,6 +3987,136 @@ NTSTATUS MountManagerUnmount (int nDosDriveNo) return ntStatus; } +typedef struct +{ + MOUNT_STRUCT* mount; PEXTENSION NewExtension; + NTSTATUS Status; + KEVENT WorkItemCompletedEvent; +} UpdateFsVolumeInformationWorkItemArgs; + +static NTSTATUS UpdateFsVolumeInformation (MOUNT_STRUCT* mount, PEXTENSION NewExtension); + +static VOID UpdateFsVolumeInformationWorkItemRoutine (PDEVICE_OBJECT rootDeviceObject, UpdateFsVolumeInformationWorkItemArgs *arg) +{ + arg->Status = UpdateFsVolumeInformation (arg->mount, arg->NewExtension); + KeSetEvent (&arg->WorkItemCompletedEvent, IO_NO_INCREMENT, FALSE); +} + +static NTSTATUS UpdateFsVolumeInformation (MOUNT_STRUCT* mount, PEXTENSION NewExtension) +{ + HANDLE volumeHandle; + PFILE_OBJECT volumeFileObject; + ULONG labelLen = (ULONG) wcslen (mount->wszLabel); + BOOL bIsNTFS = FALSE; + ULONG labelMaxLen, labelEffectiveLen; + + if ((KeGetCurrentIrql() >= APC_LEVEL) || VC_KeAreAllApcsDisabled()) + { + UpdateFsVolumeInformationWorkItemArgs args; + + PIO_WORKITEM workItem = IoAllocateWorkItem (RootDeviceObject); + if (!workItem) + return STATUS_INSUFFICIENT_RESOURCES; + + args.mount = mount; + args.NewExtension = NewExtension; + + KeInitializeEvent (&args.WorkItemCompletedEvent, SynchronizationEvent, FALSE); + IoQueueWorkItem (workItem, UpdateFsVolumeInformationWorkItemRoutine, DelayedWorkQueue, &args); + + KeWaitForSingleObject (&args.WorkItemCompletedEvent, Executive, KernelMode, FALSE, NULL); + IoFreeWorkItem (workItem); + + return args.Status; + } + + __try + { + if (NT_SUCCESS (TCOpenFsVolume (NewExtension, &volumeHandle, &volumeFileObject))) + { + __try + { + ULONG fsStatus; + + if (NT_SUCCESS (TCFsctlCall (volumeFileObject, FSCTL_IS_VOLUME_DIRTY, NULL, 0, &fsStatus, sizeof (fsStatus))) + && (fsStatus & VOLUME_IS_DIRTY)) + { + mount->FilesystemDirty = TRUE; + } + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + mount->FilesystemDirty = TRUE; + } + + // detect if the filesystem is NTFS or FAT + __try + { + NTFS_VOLUME_DATA_BUFFER ntfsData; + if (NT_SUCCESS (TCFsctlCall (volumeFileObject, FSCTL_GET_NTFS_VOLUME_DATA, NULL, 0, &ntfsData, sizeof (ntfsData)))) + { + bIsNTFS = TRUE; + } + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + bIsNTFS = FALSE; + } + + NewExtension->bIsNTFS = bIsNTFS; + mount->bIsNTFS = bIsNTFS; + + if (labelLen > 0) + { + if (bIsNTFS) + labelMaxLen = 32; // NTFS maximum label length + else + labelMaxLen = 11; // FAT maximum label length + + // calculate label effective length + labelEffectiveLen = labelLen > labelMaxLen? labelMaxLen : labelLen; + + // correct the label in the device + memset (&NewExtension->wszLabel[labelEffectiveLen], 0, 33 - labelEffectiveLen); + memcpy (mount->wszLabel, NewExtension->wszLabel, 33); + + // set the volume label + __try + { + IO_STATUS_BLOCK ioblock; + ULONG labelInfoSize = sizeof(FILE_FS_LABEL_INFORMATION) + (labelEffectiveLen * sizeof(WCHAR)); + FILE_FS_LABEL_INFORMATION* labelInfo = (FILE_FS_LABEL_INFORMATION*) TCalloc (labelInfoSize); + if (labelInfo) + { + labelInfo->VolumeLabelLength = labelEffectiveLen * sizeof(WCHAR); + memcpy (labelInfo->VolumeLabel, mount->wszLabel, labelInfo->VolumeLabelLength); + + if (STATUS_SUCCESS == ZwSetVolumeInformationFile (volumeHandle, &ioblock, labelInfo, labelInfoSize, FileFsLabelInformation)) + { + mount->bDriverSetLabel = TRUE; + NewExtension->bDriverSetLabel = TRUE; + } + + TCfree(labelInfo); + } + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + + } + } + + TCCloseFsVolume (volumeHandle, volumeFileObject); + } + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + + } + + return STATUS_SUCCESS; +} + NTSTATUS MountDevice (PDEVICE_OBJECT DeviceObject, MOUNT_STRUCT *mount) { @@ -3386,12 +4204,6 @@ NTSTATUS MountDevice (PDEVICE_OBJECT DeviceObject, MOUNT_STRUCT *mount) { if (mount->nReturnCode == 0) { - HANDLE volumeHandle; - PFILE_OBJECT volumeFileObject; - ULONG labelLen = (ULONG) wcslen (mount->wszLabel); - BOOL bIsNTFS = FALSE; - ULONG labelMaxLen, labelEffectiveLen; - Dump ("Mount SUCCESS TC code = 0x%08x READ-ONLY = %d\n", mount->nReturnCode, NewExtension->bReadOnly); if (NewExtension->bReadOnly) @@ -3412,88 +4224,24 @@ NTSTATUS MountDevice (PDEVICE_OBJECT DeviceObject, MOUNT_STRUCT *mount) } if (mount->bMountManager) + { MountManagerMount (mount); + // We create symbolic link even if mount manager is notified of + // arriving volume as it apparently sometimes fails to create the link + CreateDriveLink (mount->nDosDriveNo); + } NewExtension->bMountManager = mount->bMountManager; - // We create symbolic link even if mount manager is notified of - // arriving volume as it apparently sometimes fails to create the link - CreateDriveLink (mount->nDosDriveNo); - mount->FilesystemDirty = FALSE; - if (NT_SUCCESS (TCOpenFsVolume (NewExtension, &volumeHandle, &volumeFileObject))) + if (mount->bMountManager) { - __try - { - ULONG fsStatus; - - if (NT_SUCCESS (TCFsctlCall (volumeFileObject, FSCTL_IS_VOLUME_DIRTY, NULL, 0, &fsStatus, sizeof (fsStatus))) - && (fsStatus & VOLUME_IS_DIRTY)) - { - mount->FilesystemDirty = TRUE; - } - } - __except (EXCEPTION_EXECUTE_HANDLER) - { - mount->FilesystemDirty = TRUE; - } - - // detect if the filesystem is NTFS or FAT - __try - { - NTFS_VOLUME_DATA_BUFFER ntfsData; - if (NT_SUCCESS (TCFsctlCall (volumeFileObject, FSCTL_GET_NTFS_VOLUME_DATA, NULL, 0, &ntfsData, sizeof (ntfsData)))) - { - bIsNTFS = TRUE; - } - } - __except (EXCEPTION_EXECUTE_HANDLER) - { - bIsNTFS = FALSE; - } - - NewExtension->bIsNTFS = bIsNTFS; - mount->bIsNTFS = bIsNTFS; - - if (labelLen > 0) + NTSTATUS updateStatus = UpdateFsVolumeInformation (mount, NewExtension); + if (!NT_SUCCESS (updateStatus)) { - if (bIsNTFS) - labelMaxLen = 32; // NTFS maximum label length - else - labelMaxLen = 11; // FAT maximum label length - - // calculate label effective length - labelEffectiveLen = labelLen > labelMaxLen? labelMaxLen : labelLen; - - // correct the label in the device - memset (&NewExtension->wszLabel[labelEffectiveLen], 0, 33 - labelEffectiveLen); - memcpy (mount->wszLabel, NewExtension->wszLabel, 33); - - // set the volume label - __try - { - IO_STATUS_BLOCK ioblock; - ULONG labelInfoSize = sizeof(FILE_FS_LABEL_INFORMATION) + (labelEffectiveLen * sizeof(WCHAR)); - FILE_FS_LABEL_INFORMATION* labelInfo = (FILE_FS_LABEL_INFORMATION*) TCalloc (labelInfoSize); - labelInfo->VolumeLabelLength = labelEffectiveLen * sizeof(WCHAR); - memcpy (labelInfo->VolumeLabel, mount->wszLabel, labelInfo->VolumeLabelLength); - - if (STATUS_SUCCESS == ZwSetVolumeInformationFile (volumeHandle, &ioblock, labelInfo, labelInfoSize, FileFsLabelInformation)) - { - mount->bDriverSetLabel = TRUE; - NewExtension->bDriverSetLabel = TRUE; - } - - TCfree(labelInfo); - } - __except (EXCEPTION_EXECUTE_HANDLER) - { - - } + Dump ("MountDevice: UpdateFsVolumeInformation failed with status 0x%08x\n", updateStatus); } - - TCCloseFsVolume (volumeHandle, volumeFileObject); } } else @@ -3507,6 +4255,20 @@ NTSTATUS MountDevice (PDEVICE_OBJECT DeviceObject, MOUNT_STRUCT *mount) } } +typedef struct +{ + UNMOUNT_STRUCT *unmountRequest; PDEVICE_OBJECT deviceObject; BOOL ignoreOpenFiles; + NTSTATUS Status; + KEVENT WorkItemCompletedEvent; +} UnmountDeviceWorkItemArgs; + + +static VOID UnmountDeviceWorkItemRoutine (PDEVICE_OBJECT rootDeviceObject, UnmountDeviceWorkItemArgs *arg) +{ + arg->Status = UnmountDevice (arg->unmountRequest, arg->deviceObject, arg->ignoreOpenFiles); + KeSetEvent (&arg->WorkItemCompletedEvent, IO_NO_INCREMENT, FALSE); +} + NTSTATUS UnmountDevice (UNMOUNT_STRUCT *unmountRequest, PDEVICE_OBJECT deviceObject, BOOL ignoreOpenFiles) { PEXTENSION extension = deviceObject->DeviceExtension; @@ -3514,6 +4276,27 @@ NTSTATUS UnmountDevice (UNMOUNT_STRUCT *unmountRequest, PDEVICE_OBJECT deviceObj HANDLE volumeHandle; PFILE_OBJECT volumeFileObject; + if ((KeGetCurrentIrql() >= APC_LEVEL) || VC_KeAreAllApcsDisabled()) + { + UnmountDeviceWorkItemArgs args; + + PIO_WORKITEM workItem = IoAllocateWorkItem (RootDeviceObject); + if (!workItem) + return STATUS_INSUFFICIENT_RESOURCES; + + args.deviceObject = deviceObject; + args.unmountRequest = unmountRequest; + args.ignoreOpenFiles = ignoreOpenFiles; + + KeInitializeEvent (&args.WorkItemCompletedEvent, SynchronizationEvent, FALSE); + IoQueueWorkItem (workItem, UnmountDeviceWorkItemRoutine, DelayedWorkQueue, &args); + + KeWaitForSingleObject (&args.WorkItemCompletedEvent, Executive, KernelMode, FALSE, NULL); + IoFreeWorkItem (workItem); + + return args.Status; + } + Dump ("UnmountDevice %d\n", extension->nDosDriveNo); ntStatus = TCOpenFsVolume (extension, &volumeHandle, &volumeFileObject); @@ -3784,18 +4567,35 @@ NTSTATUS TCCompleteDiskIrp (PIRP irp, NTSTATUS status, ULONG_PTR information) } -size_t GetCpuCount () +size_t GetCpuCount (WORD* pGroupCount) { - KAFFINITY activeCpuMap = KeQueryActiveProcessors(); - size_t mapSize = sizeof (activeCpuMap) * 8; size_t cpuCount = 0; + if (KeQueryActiveGroupCountPtr && KeQueryActiveProcessorCountExPtr) + { + USHORT i, groupCount = KeQueryActiveGroupCountPtr (); + for (i = 0; i < groupCount; i++) + { + cpuCount += (size_t) KeQueryActiveProcessorCountExPtr (i); + } - while (mapSize--) + if (pGroupCount) + *pGroupCount = groupCount; + } + else { - if (activeCpuMap & 1) - ++cpuCount; + KAFFINITY activeCpuMap = KeQueryActiveProcessors(); + size_t mapSize = sizeof (activeCpuMap) * 8; - activeCpuMap >>= 1; + while (mapSize--) + { + if (activeCpuMap & 1) + ++cpuCount; + + activeCpuMap >>= 1; + } + + if (pGroupCount) + *pGroupCount = 1; } if (cpuCount == 0) @@ -3804,6 +4604,35 @@ size_t GetCpuCount () return cpuCount; } +USHORT GetCpuGroup (size_t index) +{ + if (KeQueryActiveGroupCountPtr && KeQueryActiveProcessorCountExPtr) + { + USHORT i, groupCount = KeQueryActiveGroupCountPtr (); + size_t cpuCount = 0; + for (i = 0; i < groupCount; i++) + { + cpuCount += (size_t) KeQueryActiveProcessorCountExPtr (i); + if (cpuCount >= index) + { + return i; + } + } + } + + return 0; +} + +void SetThreadCpuGroupAffinity (USHORT index) +{ + if (KeSetSystemGroupAffinityThreadPtr) + { + GROUP_AFFINITY groupAffinity = {0}; + groupAffinity.Mask = ~0ULL; + groupAffinity.Group = index; + KeSetSystemGroupAffinityThreadPtr (&groupAffinity, NULL); + } +} void EnsureNullTerminatedString (wchar_t *str, size_t maxSizeInBytes) { @@ -3815,7 +4644,7 @@ void EnsureNullTerminatedString (wchar_t *str, size_t maxSizeInBytes) void *AllocateMemoryWithTimeout (size_t size, int retryDelay, int timeout) { LARGE_INTEGER waitInterval; - waitInterval.QuadPart = retryDelay * -10000; + waitInterval.QuadPart = ((LONGLONG)retryDelay) * -10000; ASSERT (KeGetCurrentIrql() <= APC_LEVEL); ASSERT (retryDelay > 0 && retryDelay <= timeout); @@ -3963,11 +4792,26 @@ NTSTATUS ReadRegistryConfigFlags (BOOL driverEntry) if (flags & TC_DRIVER_CONFIG_CACHE_BOOT_PIM) CacheBootPim = TRUE; + + if (flags & VC_DRIVER_CONFIG_BLOCK_SYS_TRIM) + BlockSystemTrimCommand = TRUE; + + /* clear VC_DRIVER_CONFIG_CLEAR_KEYS_ON_NEW_DEVICE_INSERTION if it is set */ + if (flags & VC_DRIVER_CONFIG_CLEAR_KEYS_ON_NEW_DEVICE_INSERTION) + { + flags ^= VC_DRIVER_CONFIG_CLEAR_KEYS_ON_NEW_DEVICE_INSERTION; + WriteRegistryConfigFlags (flags); + } + + RamEncryptionActivated = (flags & VC_DRIVER_CONFIG_ENABLE_RAM_ENCRYPTION) ? TRUE : FALSE; } EnableHwEncryption ((flags & TC_DRIVER_CONFIG_DISABLE_HARDWARE_ENCRYPTION) ? FALSE : TRUE); + EnableCpuRng ((flags & VC_DRIVER_CONFIG_ENABLE_CPU_RNG) ? TRUE : FALSE); EnableExtendedIoctlSupport = (flags & TC_DRIVER_CONFIG_ENABLE_EXTENDED_IOCTL)? TRUE : FALSE; + AllowTrimCommand = (flags & VC_DRIVER_CONFIG_ALLOW_NONSYS_TRIM)? TRUE : FALSE; + AllowWindowsDefrag = (flags & VC_DRIVER_CONFIG_ALLOW_WINDOWS_DEFRAG)? TRUE : FALSE; } else status = STATUS_INVALID_PARAMETER; @@ -3983,6 +4827,65 @@ NTSTATUS ReadRegistryConfigFlags (BOOL driverEntry) TCfree (data); } + if (driverEntry && NT_SUCCESS (TCReadRegistryKey (&name, VC_ENCRYPTION_IO_REQUEST_COUNT, &data))) + { + if (data->Type == REG_DWORD) + EncryptionIoRequestCount = *(uint32 *) data->Data; + + TCfree (data); + } + + if (driverEntry && NT_SUCCESS (TCReadRegistryKey (&name, VC_ENCRYPTION_ITEM_COUNT, &data))) + { + if (data->Type == REG_DWORD) + EncryptionItemCount = *(uint32 *) data->Data; + + TCfree (data); + } + + if (driverEntry && NT_SUCCESS (TCReadRegistryKey (&name, VC_ENCRYPTION_FRAGMENT_SIZE, &data))) + { + if (data->Type == REG_DWORD) + EncryptionFragmentSize = *(uint32 *) data->Data; + + TCfree (data); + } + + if (driverEntry) + { + if (EncryptionIoRequestCount < TC_ENC_IO_QUEUE_PREALLOCATED_IO_REQUEST_COUNT) + EncryptionIoRequestCount = TC_ENC_IO_QUEUE_PREALLOCATED_IO_REQUEST_COUNT; + else if (EncryptionIoRequestCount > TC_ENC_IO_QUEUE_PREALLOCATED_IO_REQUEST_MAX_COUNT) + EncryptionIoRequestCount = TC_ENC_IO_QUEUE_PREALLOCATED_IO_REQUEST_MAX_COUNT; + + if ((EncryptionItemCount == 0) || (EncryptionItemCount > (EncryptionIoRequestCount / 2))) + EncryptionItemCount = EncryptionIoRequestCount / 2; + + /* EncryptionFragmentSize value in registry is expressed in KiB */ + /* Maximum allowed value for EncryptionFragmentSize is 2048 KiB */ + EncryptionFragmentSize *= 1024; + if (EncryptionFragmentSize == 0) + EncryptionFragmentSize = TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE; + else if (EncryptionFragmentSize > (8 * TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE)) + EncryptionFragmentSize = 8 * TC_ENC_IO_QUEUE_MAX_FRAGMENT_SIZE; + + + } + + if (driverEntry && NT_SUCCESS (TCReadRegistryKey (&name, VC_ERASE_KEYS_SHUTDOWN, &data))) + { + if (data->Type == REG_DWORD) + { + if (*((uint32 *) data->Data)) + EraseKeysOnShutdown = TRUE; + else + EraseKeysOnShutdown = FALSE; + } + + TCfree (data); + } + + return status; } @@ -4172,7 +5075,7 @@ BOOL IsOSAtLeast (OSVersionEnum reqMinOS) >= (major << 16 | minor << 8)); } -NTSTATUS NTAPI KeSaveExtendedProcessorState ( +NTSTATUS NTAPI KeSaveExtendedProcessorStateVC ( __in ULONG64 Mask, PXSTATE_SAVE XStateSave ) @@ -4187,7 +5090,7 @@ NTSTATUS NTAPI KeSaveExtendedProcessorState ( } } -VOID NTAPI KeRestoreExtendedProcessorState ( +VOID NTAPI KeRestoreExtendedProcessorStateVC ( PXSTATE_SAVE XStateSave ) { @@ -4195,4 +5098,12 @@ VOID NTAPI KeRestoreExtendedProcessorState ( { (KeRestoreExtendedProcessorStatePtr) (XStateSave); } -}
\ No newline at end of file +} + +BOOLEAN VC_KeAreAllApcsDisabled (VOID) +{ + if (KeAreAllApcsDisabledPtr) + return (KeAreAllApcsDisabledPtr) (); + else + return FALSE; +} |