参考教程:楚狂人的《驱动编程基础》
实现功能:文件拷贝,涉及文件操作的几个基本函数:ZwCreateFile,ZwReadFile,ZwWriteFile
NTSTATUS MyCopyFile(PUNICODE_STRING target_path,PUNICODE_STRING source_path) {
HANDLE target=NULL,source=NULL;
PVOID buffer=NULL; LARGE_INTEGER offset={0}; IO_STATUS_BLOCK io_status={0}; NTSTATUS status; OBJECT_ATTRIBUTES source_attributes,target_attributes; IO_STATUS_BLOCK io_status_source,io_status_target; int length; buffer=(PWCHAR)ExAllocatePoolWithTag(NonPagedPool,4096,'mMyM'); if(buffer==NULL) { DbgPrint("allocate failed!"); }
do{ //open source file InitializeObjectAttributes(&source_attributes,source_path,OBJ_CASE_INSENSITIVE|OBJ_KERNEL_HANDLE,NULL,NULL); //为了初始化object_attributes status=ZwCreateFile(&source, //out GENERIC_READ|GENERIC_WRITE, &source_attributes, &io_status_source, //out 返回结果 NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, //执行期间别的操作访问允许权限 FILE_OPEN_IF, FILE_NON_DIRECTORY_FILE|FILE_RANDOM_ACCESS|FILE_SYNCHRONOUS_IO_NONALERT, NULL,0); if(status==STATUS_SUCCESS) DbgPrint("open source success ~~\n"); else DbgPrint("open source fail^^\n");
//open target file InitializeObjectAttributes(&target_attributes,target_path,OBJ_CASE_INSENSITIVE|OBJ_KERNEL_HANDLE,NULL,NULL);
status=ZwCreateFile(&target, //out GENERIC_READ|GENERIC_WRITE, &target_attributes, &io_status_target, //out 返回结果 NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, //执行期间别的操作访问允许权限 FILE_OPEN_IF, FILE_NON_DIRECTORY_FILE|FILE_RANDOM_ACCESS|FILE_SYNCHRONOUS_IO_NONALERT, NULL,0); if(status==STATUS_SUCCESS) DbgPrint("open target success ~~\n"); else DbgPrint("open target fail^^\n"); while(1) { length=4*1024; 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( target,NULL,NULL,NULL,&io_status, buffer,length,&offset,NULL); if(!NT_SUCCESS(status)) break; offset.QuadPart+=length; } }while(0); DbgPrint("%d\n",length); if(target!=NULL) ZwClose(target); if(source!=NULL) ZwClose(source); if(buffer!=NULL) ExFreePool(buffer); return STATUS_SUCCESS; }
DriverEntry函数添加内容如下:
NTSTATUS ntstatus; UNICODE_STRING src=RTL_CONSTANT_STRING(L"\\??\\D:\\a.dat"); UNICODE_STRING tar=RTL_CONSTANT_STRING(L"\\??\\D:\\b.dat"); ntstatus=MyCopyFile(&tar,&src); if(ntstatus!=STATUS_SUCCESS) DbgPrint("copy fail\n"); else DbgPrint("copy successful\n");