頭文件1:
/***************************************************************************************
* AUTHOR :
* DATE : 2016
* MODULE : struct.h
*
* Command:
* 驅動的頭文件
*
* Description:
* 定義一些常量,避免重復勞動; 您可以在此添加需要的函數/結構體
*
****************************************************************************************
Copyright (C) 2009 .
****************************************************************************************/
#pragma once
#include <ntddk.h>
typedef long LONG;
typedef unsigned char BOOL, *PBOOL;
typedef unsigned char BYTE, *PBYTE;
typedef unsigned long DWORD, *PDWORD;
typedef unsigned short WORD, *PWORD;
typedef void *HMODULE;
typedef long NTSTATUS, *PNTSTATUS;
typedef unsigned long DWORD;
typedef DWORD * PDWORD;
typedef unsigned long ULONG;
typedef unsigned long ULONG_PTR;
typedef ULONG *PULONG;
typedef unsigned short WORD;
typedef unsigned char BYTE;
typedef unsigned char UCHAR;
typedef unsigned short USHORT;
typedef void *PVOID;
typedef BYTE BOOLEAN;
#define SEC_IMAGE 0x01000000
//----------------------------------------------------
// PEB
#pragma pack(4)
typedef struct _PEB_LDR_DATA
{
ULONG Length;
BOOLEAN Initialized;
PVOID SsHandle;
LIST_ENTRY InLoadOrderModuleList;
LIST_ENTRY InMemoryOrderModuleList;
LIST_ENTRY InInitializationOrderModuleList;
} PEB_LDR_DATA, *PPEB_LDR_DATA;
#pragma pack()
typedef struct _PEB_ORIG {
BYTE Reserved1[2];
BYTE BeingDebugged;
BYTE Reserved2[229];
PVOID Reserved3[59];
ULONG SessionId;
} PEB_ORIG, *PPEB_ORIG;
typedef void (*PPEBLOCKROUTINE)(PVOID PebLock);
struct _PEB_FREE_BLOCK {
struct _PEB_FREE_BLOCK *Next;
ULONG Size;
};
typedef struct _PEB_FREE_BLOCK PEB_FREE_BLOCK;
typedef struct _PEB_FREE_BLOCK *PPEB_FREE_BLOCK;
typedef struct _RTL_DRIVE_LETTER_CURDIR {
USHORT Flags;
USHORT Length;
ULONG TimeStamp;
UNICODE_STRING DosPath;
} RTL_DRIVE_LETTER_CURDIR, *PRTL_DRIVE_LETTER_CURDIR;
typedef struct _RTL_USER_PROCESS_PARAMETERS {
ULONG MaximumLength;
ULONG Length;
ULONG Flags;
ULONG DebugFlags;
PVOID ConsoleHandle;
ULONG ConsoleFlags;
HANDLE StdInputHandle;
HANDLE StdOutputHandle;
HANDLE StdErrorHandle;
UNICODE_STRING CurrentDirectoryPath;
HANDLE CurrentDirectoryHandle;
UNICODE_STRING DllPath;
UNICODE_STRING ImagePathName;
UNICODE_STRING CommandLine;
PVOID Environment;
ULONG StartingPositionLeft;
ULONG StartingPositionTop;
ULONG Width;
ULONG Height;
ULONG CharWidth;
ULONG CharHeight;
ULONG ConsoleTextAttributes;
ULONG WindowFlags;
ULONG ShowWindowFlags;
UNICODE_STRING WindowTitle;
UNICODE_STRING DesktopName;
UNICODE_STRING ShellInfo;
UNICODE_STRING RuntimeData;
RTL_DRIVE_LETTER_CURDIR DLCurrentDirectory[0x20];
} RTL_USER_PROCESS_PARAMETERS, *PRTL_USER_PROCESS_PARAMETERS;
typedef struct _PEB {
BOOLEAN InheritedAddressSpace;
BOOLEAN ReadImageFileExecOptions;
BOOLEAN BeingDebugged;
BOOLEAN Spare;
HANDLE Mutant;
PVOID ImageBaseAddress;
PPEB_LDR_DATA LoaderData;
PRTL_USER_PROCESS_PARAMETERS ProcessParameters;
PVOID SubSystemData;
PVOID ProcessHeap;
PVOID FastPebLock;
PPEBLOCKROUTINE FastPebLockRoutine;
PPEBLOCKROUTINE FastPebUnlockRoutine;
ULONG EnvironmentUpdateCount;
PVOID *KernelCallbackTable;
PVOID EventLogSection;
PVOID EventLog;
PPEB_FREE_BLOCK FreeList;
ULONG TlsExpansionCounter;
PVOID TlsBitmap;
ULONG TlsBitmapBits[0x2];
PVOID ReadOnlySharedMemoryBase;
PVOID ReadOnlySharedMemoryHeap;
PVOID *ReadOnlyStaticServerData;
PVOID AnsiCodePageData;
PVOID OemCodePageData;
PVOID UnicodeCaseTableData;
ULONG NumberOfProcessors;
ULONG NtGlobalFlag;
BYTE Spare2[0x4];
LARGE_INTEGER CriticalSectionTimeout;
ULONG HeapSegmentReserve;
ULONG HeapSegmentCommit;
ULONG HeapDeCommitTotalFreeThreshold;
ULONG HeapDeCommitFreeBlockThreshold;
ULONG NumberOfHeaps;
ULONG MaximumNumberOfHeaps;
PVOID **ProcessHeaps;
PVOID GdiSharedHandleTable;
PVOID ProcessStarterHelper;
PVOID GdiDCAttributeList;
PVOID LoaderLock;
ULONG OSMajorVersion;
ULONG OSMinorVersion;
ULONG OSBuildNumber;
ULONG OSPlatformId;
ULONG ImageSubSystem;
ULONG ImageSubSystemMajorVersion;
ULONG ImageSubSystemMinorVersion;
ULONG GdiHandleBuffer[0x22];
ULONG PostProcessInitRoutine;
ULONG TlsExpansionBitmap;
BYTE TlsExpansionBitmapBits[0x80];
ULONG SessionId;
} PEB, *PPEB;
typedef struct _SYSTEM_PROCESS_INFORMATION {
ULONG NextEntryOffset;
ULONG NumberOfThreads;
LARGE_INTEGER SpareLi1;
LARGE_INTEGER SpareLi2;
LARGE_INTEGER SpareLi3;
LARGE_INTEGER CreateTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER KernelTime;
UNICODE_STRING ImageName;
KPRIORITY BasePriority;
HANDLE UniqueProcessId;
HANDLE InheritedFromUniqueProcessId;
ULONG HandleCount;
ULONG SpareUl2;
ULONG SpareUl3;
ULONG PeakVirtualSize;
ULONG VirtualSize;
ULONG PageFaultCount;
ULONG PeakWorkingSetSize;
ULONG WorkingSetSize;
ULONG QuotaPeakPagedPoolUsage;
ULONG QuotaPagedPoolUsage;
ULONG QuotaPeakNonPagedPoolUsage;
ULONG QuotaNonPagedPoolUsage;
ULONG PagefileUsage;
ULONG PeakPagefileUsage;
ULONG PrivatePageCount;
} SYSTEM_PROCESS_INFORMATION, *PSYSTEM_PROCESS_INFORMATION;
typedef struct _SYSTEM_THREAD_INFORMATION {
LARGE_INTEGER KernelTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER CreateTime;
ULONG WaitTime;
PVOID StartAddress;
CLIENT_ID ClientId;
KPRIORITY Priority;
LONG BasePriority;
ULONG ContextSwitches;
ULONG ThreadState;
ULONG WaitReason;
} SYSTEM_THREAD_INFORMATION, *PSYSTEM_THREAD_INFORMATION;
struct _SYSTEM_THREADS
{
LARGE_INTEGER KernelTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER CreateTime;
ULONG WaitTime;
PVOID StartAddress;
CLIENT_ID ClientIs;
KPRIORITY Priority;
KPRIORITY BasePriority;
ULONG ContextSwitchCount;
ULONG ThreadState;
KWAIT_REASON WaitReason;
};
struct _SYSTEM_PROCESSES
{
ULONG NextEntryDelta;
ULONG ThreadCount;
ULONG Reserved[6];
LARGE_INTEGER CreateTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER KernelTime;
UNICODE_STRING ProcessName;
KPRIORITY BasePriority;
ULONG ProcessId;
ULONG InheritedFromProcessId;
ULONG HandleCount;
ULONG Reserved2[2];
VM_COUNTERS VmCounters;
IO_COUNTERS IoCounters; //windows 2000 only
struct _SYSTEM_THREADS Threads[1];
};
typedef struct _HANDLE_TABLE_ENTRY_INFO
{
ULONG AuditMask;
} HANDLE_TABLE_ENTRY_INFO, *PHANDLE_TABLE_ENTRY_INFO;
typedef struct _HANDLE_TABLE_ENTRY
{
union
{
PVOID Object;
ULONG_PTR ObAttributes;
PHANDLE_TABLE_ENTRY_INFO InfoTable;
ULONG_PTR Value;
};
union
{
ULONG GrantedAccess;
struct
{
USHORT GrantedAccessIndex;
USHORT CreatorBackTraceIndex;
};
LONG NextFreeTableEntry;
};
} HANDLE_TABLE_ENTRY, *PHANDLE_TABLE_ENTRY;
typedef struct _HANDLE_TABLE
{
ULONG TableCode;
PEPROCESS QuotaProcess;
PVOID UniqueProcessId;
ULONG HandleTableLock[4];
LIST_ENTRY HandleTableList;
ULONG HandleContentionEvent;
PVOID DebugInfo;
LONG ExtraInfoPages;
ULONG FirstFree;
ULONG LastFree;
ULONG NextHandleNeedingPool;
LONG HandleCount;
union
{
ULONG Flags;
UCHAR StrictFIFO:1;
};
} HANDLE_TABLE, *PHANDLE_TABLE;
typedef struct _OBJECT_TYPE_INITIALIZER {
USHORT Length;
BOOLEAN UseDefaultObject;
BOOLEAN CaseInsensitive;
ULONG InvalidAttributes;
GENERIC_MAPPING GenericMapping;
ULONG ValidAccessMask;
BOOLEAN SecurityRequired;
BOOLEAN MaintainHandleCount;
BOOLEAN MaintainTypeList;
POOL_TYPE PoolType;
ULONG DefaultPagedPoolCharge;
ULONG DefaultNonPagedPoolCharge;
PVOID DumpProcedure;
PVOID OpenProcedure;
PVOID CloseProcedure;
PVOID DeleteProcedure;
PVOID ParseProcedure;
PVOID SecurityProcedure;
PVOID QueryNameProcedure;
PVOID OkayToCloseProcedure;
} OBJECT_TYPE_INITIALIZER, *POBJECT_TYPE_INITIALIZER;
typedef struct _OBJECT_TYPE {
ERESOURCE Mutex;
LIST_ENTRY TypeList;
UNICODE_STRING Name; // Copy from object header for convenience
PVOID DefaultObject;
ULONG Index;
ULONG TotalNumberOfObjects;
ULONG TotalNumberOfHandles;
ULONG HighWaterNumberOfObjects;
ULONG HighWaterNumberOfHandles;
OBJECT_TYPE_INITIALIZER TypeInfo;
ULONG Key;
ERESOURCE ObjectLocks[4];
} OBJECT_TYPE, *POBJECT_TYPE;
typedef struct _OBJECT_DIRECTORY {
struct _OBJECT_DIRECTORY_ENTRY *HashBuckets[ 37 ];
ULONG Lock;
PVOID DeviceMap;
ULONG SessionId;
USHORT Reserved;
USHORT SymbolicLinkUsageCount;
} OBJECT_DIRECTORY, *POBJECT_DIRECTORY;
/*
typedef enum _KAPC_ENVIRONMENT {
OriginalApcEnvironment,
AttachedApcEnvironment,
CurrentApcEnvironment,
InsertApcEnvironment
} KAPC_ENVIRONMENT;
*/
typedef enum
{
OriginalApcEnvironment,
AttachedApcEnvironment,
CurrentApcEnvironment
} KAPC_ENVIRONMENT;
typedef struct _ProcessInfo
{
ULONG uEprocess;
ULONG uProcessId;
ULONG uCR3;
UCHAR pszImageFileName[16];
}ProcessInfo;
typedef struct _ProcessInfoList
{
LIST_ENTRY ListEntry;
ProcessInfo ProcInfo;
}ProcessInfoList;
typedef struct _ReadMemoryInfo
{
int nMemoryAddr;
int nReadSize;
int nEprocess;
}ReadMemoryInfo;
typedef struct _WriteMemoryInfo
{
int nMemoryAddr;
int nWriteSize;
int nEprocess;
BYTE *pData;
}WriteMemoryInfo;
//----------------------------------------------------
NTSYSAPI
NTSTATUS
NTAPI ZwQuerySystemInformation(
IN ULONG SystemInformationClass,
IN PVOID SystemInformation,
IN ULONG SystemInformationLength,
OUT PULONG ReturnLength);
NTSTATUS
NtOpenFile(
OUT PHANDLE FileHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN ULONG ShareAccess,
IN ULONG OpenOptions
);
NTSTATUS
ZwOpenProcess(
OUT PHANDLE ProcessHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes,
IN PCLIENT_ID ClientId
);
NTSTATUS
PsLookupProcessByProcessId(
IN HANDLE ProcessId,
OUT PEPROCESS *Process
);
HANDLE
PsGetProcessId(
IN PEPROCESS Process
);
NTSTATUS
RtlFormatCurrentUserKeyPath(
OUT PUNICODE_STRING CurrentUserKeyPath
);
VOID KeAttachProcess( PEPROCESS proc );
VOID KeDetachProcess();
頭文件2:
/***************************************************************************************
* AUTHOR :
* DATE : 2009-6-15
* MODULE : ReadMemory.H
*
* IOCTRL Sample Driver
*
* Description:
* Demonstrates communications between USER and KERNEL.
*
****************************************************************************************
* Copyright (C) 2009 .
****************************************************************************************/
#ifndef CXX_READMEMORY_H
#define CXX_READMEMORY_H
#ifdef __cplusplus
extern "C" {
#endif
#include <ntddk.h>
#include <devioctl.h>
#include "common.h"
//
// TODO: Add your include here
//
//////////////////////////////////////////////////////////////////////////
//
// TODO: Add your struct,enum(private) here
//
//////////////////////////////////////////////////////////////////////////
//***************************************************************************************
//* NAME: DriverEntry
//*
//* DESCRIPTION: Registers dispatch routines.
//*
//* PARAMETERS: pDriverObj IN
//* Address of the DRIVER_OBJECT created by NT for this driver.
//* pRegistryString IN
//* UNICODE_STRING which represents this drivers KEY in the Registry.
//*
//* IRQL: IRQL_PASSIVE_LEVEL.
//*
//* RETURNS: NTSTATUS
//***************************************************************************************
NTSTATUS DriverEntry(IN PDRIVER_OBJECT pDriverObj, IN PUNICODE_STRING pRegistryString);
//***************************************************************************************
//* NAME: DriverUnload
//*
//* DESCRIPTION: This routine is our dynamic unload entry point.
//*
//* PARAMETERS: pDriverObj IN Address of our DRIVER_OBJECT.
//*
//* IRQL: IRQL_PASSIVE_LEVEL.
//*
//* RETURNS: None
//***************************************************************************************
VOID DriverUnload(IN PDRIVER_OBJECT pDriverObj);
//***************************************************************************************
//* NAME: DispatchCreate, DispatchClose
//*
//* DESCRIPTION: This two methods are the dispatch entry point for IRP_MJ_CREATE and IRP_MJ_CLOSE
//* routines. This sample simply completes the requests with success.
//*
//* PARAMETERS: pDevObj IN Address of our DRIVER_OBJECT.
//* pIrp IN Address of the IRP.
//*
//* IRQL: IRQL_PASSIVE_LEVEL.
//*
//* RETURNS: STATUS_SUCCESS
//***************************************************************************************
NTSTATUS DispatchCreate(IN PDEVICE_OBJECT pDevObj, IN PIRP pIrp);
NTSTATUS DispatchClose(IN PDEVICE_OBJECT pDevObj, IN PIRP pIrp);
//***************************************************************************************
//* NAME: DispatchDeviceControl
//*
//* DESCRIPTION: This is the dispatch entry point for IRP_MJ_DEVICE_CONTROL.
//*
//* PARAMETERS: pDevObj IN Address of our DRIVER_OBJECT.
//* pIrp IN Address of the IRP.
//*
//* IRQL: IRQL_PASSIVE_LEVEL.
//*
//* RETURNS: NTSTATUS
//*
//* NOTES: IRP_MJ_DEVICE_CONTROL
//* Parameters:
//* Parameters.DeviceIoControl.OutputBufferLength Length of OutBuffer
//* in bytes (length of buffer from GUI)
//* Parameters.DeviceIoControl.InputBufferLength Length of InBuffer
//* in bytes (length of buffer from DRIVER)
//* Parameters.DeviceIoControl.ControlCode I/O control code
//***************************************************************************************
NTSTATUS DispatchDeviceControl(IN PDEVICE_OBJECT pDevObj, IN PIRP pIrp);
// common dispatch
//***************************************************
//* #define IRP_MJ_CREATE 0x00
//* #define IRP_MJ_CREATE_NAMED_PIPE 0x01
//* #define IRP_MJ_CLOSE 0x02
//* #define IRP_MJ_READ 0x03
//* #define IRP_MJ_WRITE 0x04
//* #define IRP_MJ_QUERY_INFORMATION 0x05
//* #define IRP_MJ_SET_INFORMATION 0x06
//* #define IRP_MJ_QUERY_EA 0x07
//* #define IRP_MJ_SET_EA 0x08
//* #define IRP_MJ_FLUSH_BUFFERS 0x09
//* #define IRP_MJ_QUERY_VOLUME_INFORMATION 0x0a
//* #define IRP_MJ_SET_VOLUME_INFORMATION 0x0b
//* #define IRP_MJ_DIRECTORY_CONTROL 0x0c
//* #define IRP_MJ_FILE_SYSTEM_CONTROL 0x0d
//* #define IRP_MJ_DEVICE_CONTROL 0x0e
//* #define IRP_MJ_INTERNAL_DEVICE_CONTROL 0x0f
//* #define IRP_MJ_SHUTDOWN 0x10
//* #define IRP_MJ_LOCK_CONTROL 0x11
//* #define IRP_MJ_CLEANUP 0x12
//* #define IRP_MJ_CREATE_MAILSLOT 0x13
//* #define IRP_MJ_QUERY_SECURITY 0x14
//* #define IRP_MJ_SET_SECURITY 0x15
//* #define IRP_MJ_POWER 0x16
//* #define IRP_MJ_SYSTEM_CONTROL 0x17
//* #define IRP_MJ_DEVICE_CHANGE 0x18
//* #define IRP_MJ_QUERY_QUOTA 0x19
//* #define IRP_MJ_SET_QUOTA 0x1a
//* #define IRP_MJ_PNP 0x1b
//* #define IRP_MJ_PNP_POWER IRP_MJ_PNP // Obsolete....
//* #define IRP_MJ_MAXIMUM_FUNCTION 0x1b -->
//***************************************************************************************
NTSTATUS DispatchCommon (IN PDEVICE_OBJECT pDevObj, IN PIRP pIrp);
ULONG GetPlantformDependentInfo(ULONG dwFlag);
//////////////////////////////////////////////////////////////////////////
#ifdef ALLOC_PRAGMA
// Allow the DriverEntry routine to be discarded once initialization is completed
#pragma alloc_text(INIT, DriverEntry)
//
#pragma alloc_text(PAGE, DriverUnload)
#pragma alloc_text(PAGE, DispatchCreate)
#pragma alloc_text(PAGE, DispatchClose)
#pragma alloc_text(PAGE, DispatchDeviceControl)
#pragma alloc_text(PAGE, DispatchCommon)
#endif // ALLOC_PRAGMA
//////////////////////////////////////////////////////////////////////////
//
// TODO: Add your module declarations here
//
#ifdef __cplusplus
}
#endif
//////////////////////////////////////////////////////////////////////////
#endif //CXX_READMEMORY_H
/* EOF */
頭文件3:
/**************************************************************************************
* AUTHOR :
* DATE : 2009-6-15
* MODULE : common.h
*
* Command:
* IOCTRL Common Header
*
* Description:
* Common data for the IoCtrl driver and application
*
****************************************************************************************
* Copyright (C) 2009 .
****************************************************************************************/
#pragma once
//#######################################################################################
// D E F I N E S
//#######################################################################################
#if DBG
#define dprintf DbgPrint
#else
#define dprintf
#endif
//不支持符號鏈接用戶相關性
#define DEVICE_NAME L"\\Device\\devNsanguo" // Driver Name
#define SYMBOLIC_LINK_NAME L"\\DosDevices\\Nsanguo" // Symbolic Link Name
#define WIN32_LINK_NAME "\\\\.\\Nsanguo" // Win32 Link Name
//支持符號鏈接用戶相關性
#define SYMBOLIC_LINK_GLOBAL_NAME L"\\DosDevices\\Global\\Nsanguo" // Symbolic Link Name
#define DATA_TO_APP "Hello World from Driver"
//
// Device IO Control Codes
//
#define IOCTL_BASE 0x800
#define MY_CTL_CODE(i) \
CTL_CODE \
( \
FILE_DEVICE_UNKNOWN, \
IOCTL_BASE + i, \
METHOD_BUFFERED, \
FILE_ANY_ACCESS \
)
#define IOCTL_READ_MEMORY MY_CTL_CODE(0)
#define IOCTL_SET_PROCESS MY_CTL_CODE(1)
#define IOCTL_GET_PROCESS MY_CTL_CODE(2)
#define IOCTL_WRITE_MEMORY MY_CTL_CODE(3)
#define IOCTL_GET_CR4 MY_CTL_CODE(4)
#define EPROCESS_SIZE 0
#define PEB_OFFSET 1
#define FILE_NAME_OFFSET 2
#define PROCESS_LINK_OFFSET 3
#define PROCESS_ID_OFFSET 4
#define EXIT_TIME_OFFSET 5
//
// TODO: Add your IOCTL define here
//
//
// TODO: Add your struct,enum(public) define here
//
PVOID g_pInfo = NULL;
/* EOF */
驅動文件:
/***************************************************************************************
* AUTHOR :
* DATE : 2009-6-15
* MODULE : ReadMemory.C
*
* Command:
* Source of IOCTRL Sample Driver
*
* Description:
* Demonstrates communications between USER and KERNEL.
*
****************************************************************************************
* Copyright (C) 2009 .
****************************************************************************************/
//#######################################################################################
//# I N C L U D E S
//#######################################################################################
#ifndef CXX_READMEMORY_H
# include "ReadMemory.h"
#endif
#include "struct.h"
//////////////////////////////////////////////////////////////////////////
//#######################################################################################
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//@@@@@@@@ D R I V E R E N T R Y P O I N T @@@@@@@@
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//#######################################################################################
NTSTATUS
DriverEntry(IN PDRIVER_OBJECT pDriverObj, IN PUNICODE_STRING pRegistryString)
{
NTSTATUS status = STATUS_SUCCESS;
UNICODE_STRING ustrLinkName;
UNICODE_STRING ustrDevName;
PDEVICE_OBJECT pDevObj;
int i = 0;
dprintf("[ReadMemory] EasySys Sample Driver\r\n"
"[ReadMemory] Compiled %s %s\r\n[ReadMemory] In DriverEntry : %wZ\r\n",
__DATE__, __TIME__, pRegistryString);
// Register dispatch routines
/*
for(i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; i++)
{
pDriverObj->MajorFunction[i] = DispatchCommon;
}
*/
pDriverObj->MajorFunction[IRP_MJ_CREATE] = DispatchCreate;
pDriverObj->MajorFunction[IRP_MJ_CLOSE] = DispatchClose;
// Dispatch routine for communications
pDriverObj->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DispatchDeviceControl;
// Unload routine
pDriverObj->DriverUnload = DriverUnload;
// Initialize the device name.
RtlInitUnicodeString(&ustrDevName, DEVICE_NAME);
// Create the device object and device extension
status = IoCreateDevice(pDriverObj,
0,
&ustrDevName,
FILE_DEVICE_UNKNOWN,
0,
FALSE,
&pDevObj);
if(!NT_SUCCESS(status))
{
dprintf("[ReadMemory] Error, IoCreateDevice = 0x%x\r\n", status);
return status;
}
//// Get a pointer to our device extension
//deviceExtension = (PDEVICE_EXTENSION) deviceObject->DeviceExtension;
//// Save a pointer to the device object
//deviceExtension->DeviceObject = deviceObject;
if(IoIsWdmVersionAvailable(1,0x10))
{
//如果是支持符號鏈接用戶相關性的系統
RtlInitUnicodeString(&ustrLinkName, SYMBOLIC_LINK_GLOBAL_NAME);
}
else
{
//不支持
RtlInitUnicodeString(&ustrLinkName, SYMBOLIC_LINK_NAME);
}
// Create a symbolic link to allow USER applications to access it.
status = IoCreateSymbolicLink(&ustrLinkName, &ustrDevName);
if(!NT_SUCCESS(status))
{
dprintf("[ReadMemory] Error, IoCreateSymbolicLink = 0x%x\r\n", status);
IoDeleteDevice(pDevObj);
return status;
}
//
// TODO: Add initialization code here.
//
//// Tell the I/O Manger to do BUFFERED IO
//deviceObject->Flags |= DO_BUFFERED_IO;
//// Save the DeviveObject
//deviceExtension->DeviceObject = deviceObject;
dprintf("[ReadMemory] DriverEntry Success\r\n");
return STATUS_SUCCESS;
}
VOID
DriverUnload(IN PDRIVER_OBJECT pDriverObj)
{
UNICODE_STRING strLink;
// Unloading - no resources to free so just return.
dprintf("[ReadMemory] Unloading...\r\n");;
//
// TODO: Add uninstall code here.
//
// Delete the symbolic link
RtlInitUnicodeString(&strLink, SYMBOLIC_LINK_NAME);
IoDeleteSymbolicLink(&strLink);
// Delete the DeviceObject
IoDeleteDevice(pDriverObj->DeviceObject);
dprintf("[ReadMemory] Unloaded Success\r\n");
return;
}
NTSTATUS
DispatchCreate(IN PDEVICE_OBJECT pDevObj, IN PIRP pIrp)
{
pIrp->IoStatus.Status = STATUS_SUCCESS;
pIrp->IoStatus.Information = 0;
dprintf("[ReadMemory] IRP_MJ_CREATE\r\n");
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
return STATUS_SUCCESS;
}
NTSTATUS
DispatchClose(IN PDEVICE_OBJECT pDevObj, IN PIRP pIrp)
{
pIrp->IoStatus.Status = STATUS_SUCCESS;
pIrp->IoStatus.Information = 0;
dprintf("[ReadMemory] IRP_MJ_CLOSE\r\n");
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
// Return success
return STATUS_SUCCESS;
}
NTSTATUS
DispatchCommon(IN PDEVICE_OBJECT pDevObj, IN PIRP pIrp)
{
pIrp->IoStatus.Status = STATUS_SUCCESS;
pIrp->IoStatus.Information = 0L;
dprintf("[ReadMemory] Common Dispatch\r\n");
IoCompleteRequest( pIrp, 0 );
// Return success
return STATUS_SUCCESS;
}
NTSTATUS
DispatchDeviceControl(IN PDEVICE_OBJECT pDevObj, IN PIRP pIrp)
{
NTSTATUS status = STATUS_INVALID_DEVICE_REQUEST; // STATUS_UNSUCCESSFUL
PIO_STACK_LOCATION pIrpStack = IoGetCurrentIrpStackLocation(pIrp);
ULONG uIoControlCode = 0;
PVOID pIoBuffer = NULL;
ULONG uInSize = 0;
ULONG uOutSize = 0;
ULONG uInfoSize = 0;
// Get the IoCtrl Code
uIoControlCode = pIrpStack->Parameters.DeviceIoControl.IoControlCode;
pIoBuffer = pIrp->AssociatedIrp.SystemBuffer;
uInSize = pIrpStack->Parameters.DeviceIoControl.InputBufferLength;
uOutSize = pIrpStack->Parameters.DeviceIoControl.OutputBufferLength;
switch(uIoControlCode)
{
case IOCTL_GET_CR4:
{
//KdBreakPoint();
dprintf("[ReadMemory] IOCTL_GET_CR4!\r\n");
ULONG uCR4 = 0;
__asm
{
cli
push eax
mov eax, cr0
and eax, not 10000h
mov cr0, eax
}
// 獲得CR4的值
__asm
{
_emit 0x0F
_emit 0x20
_emit 0xE0
mov uCR4, eax
}
__asm
{
mov eax, CR0
or eax, 10000h
mov cr0,eax
pop eax
sti
}
*(PULONG)pIoBuffer = uCR4;
uOutSize = sizeof(ULONG);
// Return success
status = STATUS_SUCCESS;
}
break;
case IOCTL_WRITE_MEMORY:
{
// KdBreakPoint();
dprintf("[ReadMemory] IOCTL_WRITE_MEMORY!\r\n");
_try
{
WriteMemoryInfo *pInfo =
(WriteMemoryInfo *)ExAllocatePool(PagedPool, sizeof(WriteMemoryInfo));
RtlCopyMemory(pInfo, pIoBuffer, sizeof(WriteMemoryInfo));
PVOID pWrite = ExAllocatePool(PagedPool, pInfo->nWriteSize);
RtlCopyMemory(pWrite, pInfo->pData, pInfo->nWriteSize);
//pInfo->pData = (PBYTE)ExAllocatePool(PagedPool, pInfo->nWriteSize);
ULONG uOldCr3 = 0;
ULONG uCurrentCr3 = *(PULONG)(pInfo->nEprocess + 0x18);
if (pInfo->nMemoryAddr == 0)
{
status = STATUS_UNSUCCESSFUL;
break;
}
__asm
{
mov eax, cr3
mov uOldCr3, eax
mov eax, uCurrentCr3
mov cr3, eax
}
__asm
{
cli
push eax
mov eax, cr0
and eax, not 10000h
mov cr0, eax
}
RtlCopyMemory((PVOID)pInfo->nMemoryAddr,
pWrite, pInfo->nWriteSize);
__asm
{
mov eax, CR0
or eax, 10000h
mov cr0,eax
pop eax
sti
}
__asm
{
mov eax, uOldCr3
mov cr3, eax
}
uOutSize = pInfo->nWriteSize;
if (pInfo != NULL)
{
ExFreePool(pInfo);
pInfo = NULL;
}
// Return success
status = STATUS_SUCCESS;
}
__except(1)
{
status = STATUS_UNSUCCESSFUL;
}
}
break;
case IOCTL_READ_MEMORY:
{
// KdBreakPoint();
dprintf("[ReadMemory] IOCTL_READ_MEMORY!\r\n");
__try
{
ReadMemoryInfo *pInfo =
(ReadMemoryInfo *)ExAllocatePool(PagedPool, sizeof(ReadMemoryInfo));
RtlCopyMemory(pInfo, pIoBuffer, sizeof(ReadMemoryInfo));
ULONG uOldCr3 = 0;
ULONG uCurrentCr3 = *(PULONG)(pInfo->nEprocess + 0x18);
if (pInfo->nMemoryAddr == 0)
{
status = STATUS_UNSUCCESSFUL;
break;
}
__asm
{
mov eax, cr3
mov uOldCr3, eax
mov eax, uCurrentCr3
mov cr3, eax
}
RtlCopyMemory(pIoBuffer,
(PVOID)pInfo->nMemoryAddr ,pInfo->nReadSize);
uOutSize = pInfo->nReadSize;
__asm
{
mov eax, uOldCr3
mov cr3, eax
}
if (pInfo != NULL)
{
ExFreePool(pInfo);
pInfo = NULL;
}
// Return success
status = STATUS_SUCCESS;
}
__except(1)
{
status = STATUS_UNSUCCESSFUL;
}
}
break;
case IOCTL_GET_PROCESS:
{
// KdBreakPoint();
dprintf("[ReadMemory] IOCTL_GET_PROCESS!\r\n");
ULONG uSize = *(PULONG)pIoBuffer;
RtlCopyMemory(pIoBuffer, g_pInfo, uSize);
uOutSize = uSize;
if (g_pInfo != NULL)
{
ExFreePool(g_pInfo);
g_pInfo;
}
// Return success
status = STATUS_SUCCESS;
}
break;
case IOCTL_SET_PROCESS:
{
// KdBreakPoint();
dprintf("[ReadMemory] IOCTL_SET_PROCESS\r\n");
// 獲得當前進程EPROCESS信息
ULONG uEprocess = 0;
__asm
{
mov eax, fs:[0x124] // _ethread
mov eax, [eax+0x44] // _kprocess
mov uEprocess, eax
}
KdPrint(("EPROCESS: 0x%08x\n", uEprocess));
LIST_ENTRY ListHead;
InitializeListHead(&ListHead);
ULONG uFirstEprocess = uEprocess;
ULONG uCount = 0;
PLIST_ENTRY pActiveProcessLinks;
ProcessInfoList *pProcssList = NULL;
ULONG uNameOffset = GetPlantformDependentInfo(FILE_NAME_OFFSET);
ULONG uPidOffset = GetPlantformDependentInfo(PROCESS_ID_OFFSET);
ULONG uLinkOffset = GetPlantformDependentInfo(PROCESS_LINK_OFFSET);
ULONG uExitTime = GetPlantformDependentInfo(EXIT_TIME_OFFSET);
// 遍歷鏈表獲得進程信息
do
{
pProcssList=
(ProcessInfoList *)ExAllocatePool(PagedPool, sizeof(ProcessInfoList));
if (pProcssList == NULL)
{
status = STATUS_INSUFFICIENT_RESOURCES;
break;
}
PLARGE_INTEGER ExitTime;
ExitTime = (PLARGE_INTEGER)(uEprocess + uExitTime);
if (ExitTime->QuadPart == 0)
{
if (*(int *)(uEprocess + uPidOffset) <= 0)
{
pProcssList->ProcInfo.uProcessId = 0;
pProcssList->ProcInfo.uEprocess = uEprocess;
pProcssList->ProcInfo.uCR3 = *(PULONG)(uEprocess + 0x18);
RtlCopyMemory(pProcssList->ProcInfo.pszImageFileName, "Idle", 16);
InsertHeadList(&ListHead, &pProcssList->ListEntry);
KdPrint(("PID: %d, EPROCESS: 0x%08x, FileName: %s, CR3: 0x%08x\n",
pProcssList->ProcInfo.uProcessId,
pProcssList->ProcInfo.uEprocess,
pProcssList->ProcInfo.pszImageFileName,
pProcssList->ProcInfo.uCR3));
}
else
{
pProcssList->ProcInfo.uEprocess = uEprocess;
pProcssList->ProcInfo.uCR3 = *(PULONG)(uEprocess + 0x18);
pProcssList->ProcInfo.uProcessId = *(PULONG)(uEprocess + uPidOffset);
RtlCopyMemory(pProcssList->ProcInfo.pszImageFileName,
(PVOID)(uEprocess + uNameOffset),
16);
InsertHeadList(&ListHead, &pProcssList->ListEntry);
KdPrint(("PID: %d, EPROCESS: 0x%08x, FileName: %s, CR3: 0x%08x\n",
pProcssList->ProcInfo.uProcessId,
pProcssList->ProcInfo.uEprocess,
pProcssList->ProcInfo.pszImageFileName,
pProcssList->ProcInfo.uCR3));
}
uCount++;
}
pActiveProcessLinks = (PLIST_ENTRY)(uEprocess + uLinkOffset);
uEprocess = (ULONG)pActiveProcessLinks->Blink - uLinkOffset;
if (uEprocess == uFirstEprocess)
{
break;
}
} while (uEprocess != 0);
KdPrint(("%d\n", uCount));
uInfoSize = sizeof(ProcessInfo) * uCount;
g_pInfo = ExAllocatePool(
PagedPool,
uInfoSize);
ProcessInfo *pTemp = NULL;
if (g_pInfo == NULL)
{
status = STATUS_UNSUCCESSFUL;
break;
}
RtlZeroMemory(g_pInfo, uInfoSize);
pTemp = (ProcessInfo *)g_pInfo;
while (!IsListEmpty(&ListHead))
{
PLIST_ENTRY pEntry = RemoveTailList(&ListHead);
pProcssList = CONTAINING_RECORD(pEntry, ProcessInfoList, ListEntry);
RtlCopyMemory(pTemp->pszImageFileName,
pProcssList->ProcInfo.pszImageFileName,
16);
pTemp->uEprocess = pProcssList->ProcInfo.uEprocess;
pTemp->uProcessId = pProcssList->ProcInfo.uProcessId;
pTemp->uCR3 = pProcssList->ProcInfo.uCR3;
// 釋放節點內存
if (pProcssList != NULL)
{
ExFreePool(pProcssList);
}
if (!IsListEmpty(&ListHead))
{
pTemp =
(ProcessInfo *)((DWORD)pTemp + sizeof(ProcessInfo));
}
}
*(PULONG)pIoBuffer = uInfoSize;
uOutSize = sizeof(ULONG);
// Return success
status = STATUS_SUCCESS;
}
break;
default:
{
// Invalid code sent
dprintf("[ReadMemory] Unknown IOCTL: 0x%X (%04X,%04X)\r\n",
uIoControlCode,
DEVICE_TYPE_FROM_CTL_CODE(uIoControlCode),
IoGetFunctionCodeFromCtlCode(uIoControlCode));
status = STATUS_INVALID_PARAMETER;
}
break;
}
if(status == STATUS_SUCCESS)
{
pIrp->IoStatus.Information = uOutSize;
}
else
{
pIrp->IoStatus.Information = 0;
}
// Complete the I/O Request
pIrp->IoStatus.Status = status;
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
return status;
}
//
// TODO: Add your module definitions here.
//
ULONG GetPlantformDependentInfo(ULONG dwFlag)
{
ULONG current_build;
ULONG ans = 0;
PsGetVersion(NULL, NULL, ¤t_build, NULL);
switch ( dwFlag )
{
case EPROCESS_SIZE:
if (current_build == 2195) ans = 0 ; // 2000,當前不支持2000,下同
if (current_build == 2600) ans = 0x25C; // xp
if (current_build == 3790) ans = 0x270; // 2003
break;
case PEB_OFFSET:
if (current_build == 2195) ans = 0;
if (current_build == 2600) ans = 0x1b0;
if (current_build == 3790) ans = 0x1a0;
break;
case FILE_NAME_OFFSET:
if (current_build == 2195) ans = 0;
if (current_build == 2600) ans = 0x174;
if (current_build == 3790) ans = 0x164;
break;
case PROCESS_LINK_OFFSET:
if (current_build == 2195) ans = 0;
if (current_build == 2600) ans = 0x088;
if (current_build == 3790) ans = 0x098;
break;
case PROCESS_ID_OFFSET:
if (current_build == 2195) ans = 0;
if (current_build == 2600) ans = 0x084;
if (current_build == 3790) ans = 0x094;
break;
case EXIT_TIME_OFFSET:
if (current_build == 2195) ans = 0;
if (current_build == 2600) ans = 0x078;
if (current_build == 3790) ans = 0x088;
break;
}
return ans;
}
/* EOF */
|