驅動開發:透過應用堆實現多次通訊

lyshark發表於2023-05-19

在前面的文章《驅動開發:運用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: me@lyshark.com

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.IoControlBufferPointer結構傳輸至核心中,而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: me@lyshark.com

// 應用層資料結構體資料
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: me@lyshark.com

#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: me@lyshark.com

#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客戶端,此時螢幕中即可看到滾動輸出效果,如此一來就實現了迴圈傳遞引數的目的。

相關文章