四、文件 註冊表 多線程

文件 註冊表 多線程

1、文件操作,內核模式下打開、創建、拷貝文件

#include <ntddk.h>


VOID DriverUnload(PDRIVER_OBJECT pDriverObject)
{
	KdPrint(("驅動成功卸載\n"));
}

void MyCopyFile(HANDLE source, HANDLE dest)
{
	NTSTATUS status;
	PVOID buffer = NULL;
	LARGE_INTEGER offset = { 0 };
	IO_STATUS_BLOCK io_status = { 0 };
	buffer = ExAllocatePool(PagedPool, 4*1024*sizeof(char));
	if (buffer == NULL)
	{
		KdPrint(("分配讀寫buffer空間失敗"));
		return;
	}
	int length = 1024 * 4;
	do
	{
		while (1)
		{
			status = ZwReadFile(source, NULL, NULL, NULL, &io_status, buffer, length, &offset, NULL);
			if (!NT_SUCCESS(status))
			{
				if (status == STATUS_END_OF_FILE)
					status = STATUS_SUCCESS;
				break;
			}
			
			length = io_status.Information;
			
			status = ZwWriteFile(dest, NULL, NULL, NULL, &io_status,buffer, length, &offset, NULL);
			if (!NT_SUCCESS(status))
				break;
			offset.QuadPart += length;
		}
	} while (0);
	if (buffer != NULL)
		ExFreePool(buffer);

}

NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObject, PUNICODE_STRING reg_path)
{
	NTSTATUS status;

	KdPrint(("%wZ",reg_path));
	UNICODE_STRING unicSourceName, unicDestName;
	RtlInitUnicodeString(&unicSourceName, L"\\??\\c:\\test\\sql.txt");
	KdPrint(("source file is: %wZ", &unicSourceName));

	RtlInitUnicodeString(&unicDestName, L"\\??\\c:\\test\\sqltest.txt");
	KdPrint(("dest file is: %wZ", &unicDestName));

	HANDLE hSourceHandle = NULL;
	HANDLE hDestHandle = NULL;
	OBJECT_ATTRIBUTES object_attributes1, object_attributes2;
	IO_STATUS_BLOCK iostatus;
	//初始化文件屬性
	InitializeObjectAttributes(
		&object_attributes1,
		&unicSourceName,
		OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
		NULL,
		NULL
	);

	InitializeObjectAttributes(
		&object_attributes2,
		&unicDestName,
		OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
		NULL,
		NULL
	);

	status = ZwCreateFile(
		&hSourceHandle,
		GENERIC_READ | GENERIC_WRITE,
		&object_attributes1,
		&iostatus,
		NULL,
		FILE_ATTRIBUTE_NORMAL,
		FILE_SHARE_READ,
		FILE_OPEN_IF,
		FILE_NON_DIRECTORY_FILE|FILE_RANDOM_ACCESS|FILE_SYNCHRONOUS_IO_NONALERT,
		NULL,
		0
	);
	if (!NT_SUCCESS(status))
	{
		KdPrint(("文件打開失敗"));
		KdPrint(("失敗原因:%d", iostatus.Information));
	}
	status = ZwCreateFile(
		&hDestHandle,
		GENERIC_READ | GENERIC_WRITE,
		&object_attributes2,
		&iostatus,
		NULL,
		FILE_ATTRIBUTE_NORMAL,
		FILE_SHARE_READ,
		FILE_OPEN_IF,
		FILE_NON_DIRECTORY_FILE|FILE_RANDOM_ACCESS | FILE_SYNCHRONOUS_IO_NONALERT,
		NULL,
		0
	);
	if (!NT_SUCCESS(status))
	{
		KdPrint(("創建文件失敗"));
		KdPrint(("失敗原因:%d", iostatus.Information));
	}

	MyCopyFile(hSourceHandle, hDestHandle);
	ZwClose(hDestHandle);
	ZwClose(hSourceHandle);

	pDriverObject->DriverUnload = DriverUnload;
	return STATUS_SUCCESS;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章