在前面的文章`《驅動開發:運用MDL映射實現多次通信》`LyShark教大家使用`MDL`的方式靈活的實現了內核態多次輸出結構體的效果,但是此種方法並不推薦大家使用原因很簡單首先內核空間比較寶貴,其次內核裡面不能分配太大且每次傳出的結構體最大不能超過`1024`個,而最終這些記憶體由於無法得到更好的釋... ...
在前面的文章《驅動開發:運用MDL映射實現多次通信》
LyShark教大家使用MDL
的方式靈活的實現了內核態多次輸出結構體的效果,但是此種方法並不推薦大家使用原因很簡單首先內核空間比較寶貴,其次內核裡面不能分配太大且每次傳出的結構體最大不能超過1024
個,而最終這些記憶體由於無法得到更好的釋放從而導致壞堆的產生,這樣的程式顯然是無法在生產環境中使用的,如下LyShark
將教大家通過在應用層申請空間來實現同等效果,此類傳遞方式也是多數ARK反內核工具中最常採用的一種。
與MDL映射相反,MDL多數處理流程在內核代碼中,而應用層開堆複雜代碼則在應用層,但內核層中同樣還是需要使用指針,只是這裡的指針僅僅只是保留基本要素即可,通過EnumProcess()
模擬枚舉進程操作,傳入的是PPROCESS_INFO
進程指針轉換,將數據傳入到PPROCESS_INFO
直接返回進程計數器即可。
// -------------------------------------------------
// R3傳輸結構體
// -------------------------------------------------
// 進程指針轉換
typedef struct
{
DWORD PID;
DWORD PPID;
}PROCESS_INFO, *PPROCESS_INFO;
// 數據存儲指針
typedef struct
{
ULONG_PTR nSize;
PVOID BufferPtr;
}BufferPointer, *pBufferPointer;
// 模擬進程枚舉
ULONG EnumProcess(PPROCESS_INFO pBuffer)
{
ULONG nCount = 0;
for (size_t i = 0; i < 10; i++)
{
pBuffer[i].PID = nCount * 2;
pBuffer[i].PPID = nCount * 4;
nCount = nCount + 1;
}
return nCount;
}
內核層核心代碼: 內核代碼中是如何通信的,首先從用戶態接收pIoBuffer
到分配的緩衝區數據,並轉換為pBufferPointer
結構,ProbeForWrite
用於檢查地址是否可寫入,接著會調用EnumProcess()
註意傳入的其實是應用層的指針,枚舉進程結束後,將進程數量nCount
通過*(PULONG)pIrp->AssociatedIrp.SystemBuffer = (ULONG)nCount
回傳給應用層,至此內核中僅僅回傳了一個長度,其他的都寫入到了應用層中。
// 署名權
// right to sign one's name on a piece of work
// PowerBy: LyShark
// Email: [email protected]
pBufferPointer pinp = (pBufferPointer)pIoBuffer;
__try
{
DbgPrint("緩衝區長度: %d \n", pinp->nSize);
DbgPrint("緩衝區基地址: %p \n", pinp->BufferPtr);
// 檢查地址是否可寫入
ProbeForWrite(pinp->BufferPtr, pinp->nSize, 1);
ULONG nCount = EnumProcess((PPROCESS_INFO)pinp->BufferPtr);
DbgPrint("進程計數 = %d \n", nCount);
if (nCount > 0)
{
// 將進程數返回給用戶
*(PULONG)pIrp->AssociatedIrp.SystemBuffer = (ULONG)nCount;
status = STATUS_SUCCESS;
}
}
__except (1)
{
status = GetExceptionCode();
DbgPrint("IOCTL_GET_EPROCESS %x \n", status);
}
// 返回通信狀態
status = STATUS_SUCCESS;
break;
應用層核心代碼: 通信的重點在於應用層,首先定義BufferPointer
用於存放緩衝區頭部指針,定義PPROCESS_INFO
則是用於後期將數據放入該容器內,函數HeapAlloc
分配一段堆空間,並HEAP_ZERO_MEMORY
將該堆空間全部填空,將這一段初始化後的空間放入到pInput.BufferPtr
緩衝區內,並計算出長度放入到pInput.nSize
緩衝區內,一切準備就緒之後,再通過DriveControl.IoControl
將BufferPointer
結構傳輸至內核中,而bRet
則是用於接收返回長度的變數。
當收到數據後,通過(PPROCESS_INFO)pInput.BufferPtr
強制轉換為指針類型,並依次pProcessInfo[i]
讀出每一個節點的元素,最後是調用HeapFree
釋放掉這段堆空間。至於輸出就很簡單了vectorProcess[x].PID
迴圈容器元素即可。
// 署名權
// right to sign one's name on a piece of work
// PowerBy: LyShark
// Email: [email protected]
// 應用層數據結構體數據
BOOL bRet = FALSE;
BufferPointer pInput = { 0 };
PPROCESS_INFO pProcessInfo = NULL;
// 分配堆空間
pInput.BufferPtr = (PVOID)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(PROCESS_INFO) * 1000);
pInput.nSize = sizeof(PROCESS_INFO) * 1000;
ULONG nRet = 0;
if (pInput.BufferPtr)
{
bRet = DriveControl.IoControl(IOCTL_IO_R3StructAll, &pInput, sizeof(BufferPointer), &nRet, sizeof(ULONG), 0);
}
std::cout << "返回結構體數量: " << nRet << std::endl;
if (bRet && nRet > 0)
{
pProcessInfo = (PPROCESS_INFO)pInput.BufferPtr;
std::vector<PROCESS_INFO> vectorProcess;
for (ULONG i = 0; i < nRet; i++)
{
vectorProcess.push_back(pProcessInfo[i]);
}
// 釋放空間
bRet = HeapFree(GetProcessHeap(), 0, pInput.BufferPtr);
std::cout << "釋放狀態: " << bRet << std::endl;
// 輸出容器內的進程ID列表
for (int x = 0; x < nRet; x++)
{
std::cout << "PID: " << vectorProcess[x].PID << " PPID: " << vectorProcess[x].PPID << std::endl;
}
}
// 關閉符號鏈接句柄
CloseHandle(DriveControl.m_hDriver);
如上就是內核層與應用層的部分代碼功能分析,接下來我將完整代碼分享出來,大家可以自行測試效果。
驅動程式WinDDK.sys
完整代碼;
// 署名權
// right to sign one's name on a piece of work
// PowerBy: LyShark
// Email: [email protected]
#define _CRT_SECURE_NO_WARNINGS
#include <ntifs.h>
#include <windef.h>
// 定義符號鏈接,一般來說修改為驅動的名字即可
#define DEVICE_NAME L"\\Device\\WinDDK"
#define LINK_NAME L"\\DosDevices\\WinDDK"
#define LINK_GLOBAL_NAME L"\\DosDevices\\Global\\WinDDK"
// 定義驅動功能號和名字,提供介面給應用程式調用
#define IOCTL_IO_R3StructAll CTL_CODE(FILE_DEVICE_UNKNOWN, 0x806, METHOD_BUFFERED, FILE_ANY_ACCESS)
// 保存一段非分頁記憶體,用於給全局變數使用
#define FILE_DEVICE_EXTENSION 4096
// -------------------------------------------------
// R3傳輸結構體
// -------------------------------------------------
// 進程指針轉換
typedef struct
{
DWORD PID;
DWORD PPID;
}PROCESS_INFO, *PPROCESS_INFO;
// 數據存儲指針
typedef struct
{
ULONG_PTR nSize;
PVOID BufferPtr;
}BufferPointer, *pBufferPointer;
// 模擬進程枚舉
ULONG EnumProcess(PPROCESS_INFO pBuffer)
{
ULONG nCount = 0;
for (size_t i = 0; i < 10; i++)
{
pBuffer[i].PID = nCount * 2;
pBuffer[i].PPID = nCount * 4;
nCount = nCount + 1;
}
return nCount;
}
// 驅動綁定預設派遣函數
NTSTATUS DefaultDispatch(PDEVICE_OBJECT _pDeviceObject, PIRP _pIrp)
{
_pIrp->IoStatus.Status = STATUS_NOT_SUPPORTED;
_pIrp->IoStatus.Information = 0;
IoCompleteRequest(_pIrp, IO_NO_INCREMENT);
return _pIrp->IoStatus.Status;
}
// 驅動卸載的處理常式
VOID DriverUnload(PDRIVER_OBJECT pDriverObj)
{
if (pDriverObj->DeviceObject)
{
UNICODE_STRING strLink;
// 刪除符號連接和設備
RtlInitUnicodeString(&strLink, LINK_NAME);
IoDeleteSymbolicLink(&strLink);
IoDeleteDevice(pDriverObj->DeviceObject);
DbgPrint("[kernel] # 驅動已卸載 \n");
}
}
// IRP_MJ_CREATE 對應的處理常式,一般不用管它
NTSTATUS DispatchCreate(PDEVICE_OBJECT pDevObj, PIRP pIrp)
{
DbgPrint("[kernel] # 驅動處理常式載入 \n");
pIrp->IoStatus.Status = STATUS_SUCCESS;
pIrp->IoStatus.Information = 0;
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
return STATUS_SUCCESS;
}
// IRP_MJ_CLOSE 對應的處理常式,一般不用管它
NTSTATUS DispatchClose(PDEVICE_OBJECT pDevObj, PIRP pIrp)
{
DbgPrint("[kernel] # 關閉派遣 \n");
pIrp->IoStatus.Status = STATUS_SUCCESS;
pIrp->IoStatus.Information = 0;
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
return STATUS_SUCCESS;
}
// IRP_MJ_DEVICE_CONTROL 對應的處理常式,驅動最重要的函數
NTSTATUS DispatchIoctl(PDEVICE_OBJECT pDevObj, PIRP pIrp)
{
NTSTATUS status = STATUS_INVALID_DEVICE_REQUEST;
PIO_STACK_LOCATION pIrpStack;
ULONG uIoControlCode;
PVOID pIoBuffer;
ULONG uInSize;
ULONG uOutSize;
// 獲得IRP里的關鍵數據
pIrpStack = IoGetCurrentIrpStackLocation(pIrp);
// 獲取控制碼
uIoControlCode = pIrpStack->Parameters.DeviceIoControl.IoControlCode;
// 輸入和輸出的緩衝區(DeviceIoControl的InBuffer和OutBuffer都是它)
pIoBuffer = pIrp->AssociatedIrp.SystemBuffer;
// EXE發送傳入數據的BUFFER長度(DeviceIoControl的nInBufferSize)
uInSize = pIrpStack->Parameters.DeviceIoControl.InputBufferLength;
// EXE接收傳出數據的BUFFER長度(DeviceIoControl的nOutBufferSize)
uOutSize = pIrpStack->Parameters.DeviceIoControl.OutputBufferLength;
// 對不同控制信號的處理流程
switch (uIoControlCode)
{
// 測試R3傳輸多次結構體
case IOCTL_IO_R3StructAll:
{
pBufferPointer pinp = (pBufferPointer)pIoBuffer;
__try
{
DbgPrint("[lyshark] 緩衝區長度: %d \n", pinp->nSize);
DbgPrint("[lyshark] 緩衝區基地址: %p \n", pinp->BufferPtr);
// 檢查地址是否可寫入
ProbeForWrite(pinp->BufferPtr, pinp->nSize, 1);
ULONG nCount = EnumProcess((PPROCESS_INFO)pinp->BufferPtr);
DbgPrint("[lyshark.com] 進程計數 = %d \n", nCount);
if (nCount > 0)
{
// 將進程數返回給用戶
*(PULONG)pIrp->AssociatedIrp.SystemBuffer = (ULONG)nCount;
status = STATUS_SUCCESS;
}
}
__except (1)
{
status = GetExceptionCode();
DbgPrint("IOCTL_GET_EPROCESS %x \n", status);
}
// 返回通信狀態
status = STATUS_SUCCESS;
break;
}
}
// 設定DeviceIoControl的*lpBytesReturned的值(如果通信失敗則返回0長度)
if (status == STATUS_SUCCESS)
{
pIrp->IoStatus.Information = uOutSize;
}
else
{
pIrp->IoStatus.Information = 0;
}
// 設定DeviceIoControl的返回值是成功還是失敗
pIrp->IoStatus.Status = status;
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
return status;
}
// 驅動的初始化工作
NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObj, PUNICODE_STRING pRegistryString)
{
NTSTATUS status = STATUS_SUCCESS;
UNICODE_STRING ustrLinkName;
UNICODE_STRING ustrDevName;
PDEVICE_OBJECT pDevObj;
// 初始化其他派遣
for (ULONG i = 0; i < IRP_MJ_MAXIMUM_FUNCTION; i++)
{
// DbgPrint("初始化派遣: %d \n", i);
pDriverObj->MajorFunction[i] = DefaultDispatch;
}
// 設置分發函數和卸載常式
pDriverObj->MajorFunction[IRP_MJ_CREATE] = DispatchCreate;
pDriverObj->MajorFunction[IRP_MJ_CLOSE] = DispatchClose;
pDriverObj->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DispatchIoctl;
pDriverObj->DriverUnload = DriverUnload;
// 創建一個設備
RtlInitUnicodeString(&ustrDevName, DEVICE_NAME);
// FILE_DEVICE_EXTENSION 創建設備時,指定設備擴展記憶體的大小,傳一個值進去,就會給設備分配一塊非頁面記憶體。
status = IoCreateDevice(pDriverObj, sizeof(FILE_DEVICE_EXTENSION), &ustrDevName, FILE_DEVICE_UNKNOWN, 0, FALSE, &pDevObj);
if (!NT_SUCCESS(status))
{
return status;
}
// 判斷支持的WDM版本,其實這個已經不需要了,純屬WIN9X和WINNT並存時代的殘留物
if (IoIsWdmVersionAvailable(1, 0x10))
{
RtlInitUnicodeString(&ustrLinkName, LINK_GLOBAL_NAME);
}
else
{
RtlInitUnicodeString(&ustrLinkName, LINK_NAME);
}
// 創建符號連接
status = IoCreateSymbolicLink(&ustrLinkName, &ustrDevName);
if (!NT_SUCCESS(status))
{
DbgPrint("創建符號鏈接失敗 \n");
IoDeleteDevice(pDevObj);
return status;
}
DbgPrint("[hello LyShark.com] # 驅動初始化完畢 \n");
// 返回載入驅動的狀態(如果返回失敗,驅動講被清除出內核空間)
return STATUS_SUCCESS;
}
應用層客戶端程式lyshark.exe
完整代碼;
// 署名權
// right to sign one's name on a piece of work
// PowerBy: LyShark
// Email: [email protected]
#include <iostream>
#include <Windows.h>
#include <vector>
#pragma comment(lib,"user32.lib")
#pragma comment(lib,"advapi32.lib")
// 定義驅動功能號和名字,提供介面給應用程式調用
#define IOCTL_IO_R3StructAll 0x806
class cDrvCtrl
{
public:
cDrvCtrl()
{
m_pSysPath = NULL;
m_pServiceName = NULL;
m_pDisplayName = NULL;
m_hSCManager = NULL;
m_hService = NULL;
m_hDriver = INVALID_HANDLE_VALUE;
}
~cDrvCtrl()
{
CloseServiceHandle(m_hService);
CloseServiceHandle(m_hSCManager);
CloseHandle(m_hDriver);
}
// 安裝驅動
BOOL Install(PCHAR pSysPath, PCHAR pServiceName, PCHAR pDisplayName)
{
m_pSysPath = pSysPath;
m_pServiceName = pServiceName;
m_pDisplayName = pDisplayName;
m_hSCManager = OpenSCManagerA(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (NULL == m_hSCManager)
{
m_dwLastError = GetLastError();
return FALSE;
}
m_hService = CreateServiceA(m_hSCManager, m_pServiceName, m_pDisplayName,
SERVICE_ALL_ACCESS, SERVICE_KERNEL_DRIVER, SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL,
m_pSysPath, NULL, NULL, NULL, NULL, NULL);
if (NULL == m_hService)
{
m_dwLastError = GetLastError();
if (ERROR_SERVICE_EXISTS == m_dwLastError)
{
m_hService = OpenServiceA(m_hSCManager, m_pServiceName, SERVICE_ALL_ACCESS);
if (NULL == m_hService)
{
CloseServiceHandle(m_hSCManager);
return FALSE;
}
}
else
{
CloseServiceHandle(m_hSCManager);
return FALSE;
}
}
return TRUE;
}
// 啟動驅動
BOOL Start()
{
if (!StartServiceA(m_hService, NULL, NULL))
{
m_dwLastError = GetLastError();
return FALSE;
}
return TRUE;
}
// 關閉驅動
BOOL Stop()
{
SERVICE_STATUS ss;
GetSvcHandle(m_pServiceName);
if (!ControlService(m_hService, SERVICE_CONTROL_STOP, &ss))
{
m_dwLastError = GetLastError();
return FALSE;
}
return TRUE;
}
// 移除驅動
BOOL Remove()
{
GetSvcHandle(m_pServiceName);
if (!DeleteService(m_hService))
{
m_dwLastError = GetLastError();
return FALSE;
}
return TRUE;
}
// 打開驅動
BOOL Open(PCHAR pLinkName)
{
if (m_hDriver != INVALID_HANDLE_VALUE)
return TRUE;
m_hDriver = CreateFileA(pLinkName, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (m_hDriver != INVALID_HANDLE_VALUE)
return TRUE;
else
return FALSE;
}
// 發送控制信號
BOOL IoControl(DWORD dwIoCode, PVOID InBuff, DWORD InBuffLen, PVOID OutBuff, DWORD OutBuffLen, DWORD *RealRetBytes)
{
DWORD dw;
BOOL b = DeviceIoControl(m_hDriver, CTL_CODE_GEN(dwIoCode), InBuff, InBuffLen, OutBuff, OutBuffLen, &dw, NULL);
if (RealRetBytes)
*RealRetBytes = dw;
return b;
}
private:
// 獲取服務句柄
BOOL GetSvcHandle(PCHAR pServiceName)
{
m_pServiceName = pServiceName;
m_hSCManager = OpenSCManagerA(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (NULL == m_hSCManager)
{
m_dwLastError = GetLastError();
return FALSE;
}
m_hService = OpenServiceA(m_hSCManager, m_pServiceName, SERVICE_ALL_ACCESS);
if (NULL == m_hService)
{
CloseServiceHandle(m_hSCManager);
return FALSE;
}
else
{
return TRUE;
}
}
// 獲取控制信號對應字元串
DWORD CTL_CODE_GEN(DWORD lngFunction)
{
return (FILE_DEVICE_UNKNOWN * 65536) | (FILE_ANY_ACCESS * 16384) | (lngFunction * 4) | METHOD_BUFFERED;
}
public:
DWORD m_dwLastError;
PCHAR m_pSysPath;
PCHAR m_pServiceName;
PCHAR m_pDisplayName;
HANDLE m_hDriver;
SC_HANDLE m_hSCManager;
SC_HANDLE m_hService;
};
void GetAppPath(char *szCurFile)
{
GetModuleFileNameA(0, szCurFile, MAX_PATH);
for (SIZE_T i = strlen(szCurFile) - 1; i >= 0; i--)
{
if (szCurFile[i] == '\\')
{
szCurFile[i + 1] = '\0';
break;
}
}
}
// -------------------------------------------------
// R3數據傳遞變數
// -------------------------------------------------
// 進程指針轉換
typedef struct
{
DWORD PID;
DWORD PPID;
}PROCESS_INFO, *PPROCESS_INFO;
// 數據存儲指針
typedef struct
{
ULONG_PTR nSize;
PVOID BufferPtr;
}BufferPointer, *pBufferPointer;
int main(int argc, char *argv[])
{
cDrvCtrl DriveControl;
// 設置驅動名稱
char szSysFile[MAX_PATH] = { 0 };
char szSvcLnkName[] = "WinDDK";;
GetAppPath(szSysFile);
strcat(szSysFile, "WinDDK.sys");
// 安裝並啟動驅動
DriveControl.Install(szSysFile, szSvcLnkName, szSvcLnkName);
DriveControl.Start();
// 打開驅動的符號鏈接
DriveControl.Open("\\\\.\\WinDDK");
// 應用層數據結構體數據
BOOL bRet = FALSE;
BufferPointer pInput = { 0 };
PPROCESS_INFO pProcessInfo = NULL;
// 分配堆空間
pInput.BufferPtr = (PVOID)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(PROCESS_INFO) * 1000);
pInput.nSize = sizeof(PROCESS_INFO) * 1000;
ULONG nRet = 0;
if (pInput.BufferPtr)
{
bRet = DriveControl.IoControl(IOCTL_IO_R3StructAll, &pInput, sizeof(BufferPointer), &nRet, sizeof(ULONG), 0);
}
std::cout << "[LyShark.com] 返回結構體數量: " << nRet << std::endl;
if (bRet && nRet > 0)
{
pProcessInfo = (PPROCESS_INFO)pInput.BufferPtr;
std::vector<PROCESS_INFO> vectorProcess;
for (ULONG i = 0; i < nRet; i++)
{
vectorProcess.push_back(pProcessInfo[i]);
}
// 釋放空間
bRet = HeapFree(GetProcessHeap(), 0, pInput.BufferPtr);
std::cout << "釋放狀態: " << bRet << std::endl;
// 輸出容器內的進程ID列表
for (int x = 0; x < nRet; x++)
{
std::cout << "PID: " << vectorProcess[x].PID << " PPID: " << vectorProcess[x].PPID << std::endl;
}
}
// 關閉符號鏈接句柄
CloseHandle(DriveControl.m_hDriver);
// 停止並卸載驅動
DriveControl.Stop();
DriveControl.Remove();
system("pause");
return 0;
}
手動編譯這兩個程式,將驅動簽名後以管理員身份運行lyshark.exe
客戶端,此時屏幕中即可看到滾動輸出效果,如此一來就實現了迴圈傳遞參數的目的。
文章出處:https://www.cnblogs.com/LyShark/p/17134596.html
版權聲明:本博客文章,除去特殊聲明 [轉載標註/參考文獻] 部分, [均為原創] 作品,禁止任何形式的轉載!