驅動開發:核心封裝WSK網路通訊介面

2022-11-03 12:03:08

本章LyShark將帶大家學習如何在核心中使用標準的Socket通訊端通訊介面,我們都知道Windows應用層下可直接呼叫WinSocket來實現網路通訊,但在核心模式下應用層API介面無法使用,核心模式下有一套專有的WSK通訊介面,我們對WSK進行封裝,讓其與應用層呼叫規範保持一致,並實現核心與核心直接通過Socket通訊的案例。

當然在早期如果需要實現網路通訊一般都會採用TDI框架,但在新版本Windows10系統上雖然依然可以使用TDI介面,但是LyShark並不推薦使用,因為微軟已經對介面擱置了,為了使WSK通訊更加易用,我們需要封裝核心層中的通訊API,新建LySocket.hpp標頭檔案,該檔案中封裝了WSK通訊API介面,其封裝格式與應用層介面保持了高度一致,當需要在核心中使用Socket通訊時可直接引入本檔案。

我們需要使用WDM驅動程式,並設定以下引數。

  • 設定屬性 -> 聯結器 -> 輸入-> 附加依賴 -> $(DDK_LIB_PATH)\Netio.lib
  • 設定屬性 -> C/C++ -> 常規 -> 設定 警告等級2級 (警告視為錯誤關閉)

設定好以後,我們就開始吧,先來看看伺服器端如何實現!

對於伺服器端來說,驅動通訊必須保證伺服器端開啟多執行緒來處理非同步請求,不然驅動載入後系統會處於等待狀態,而一旦等待則系統將會卡死,那麼對於伺服器端DriverEntry入口說我們不能讓其等待,必須使用PsCreateSystemThread來啟用系統執行緒,該函數屬於WDM的一部分,官方定義如下;

NTSTATUS PsCreateSystemThread(
  [out]           PHANDLE            ThreadHandle,
  [in]            ULONG              DesiredAccess,
  [in, optional]  POBJECT_ATTRIBUTES ObjectAttributes,
  [in, optional]  HANDLE             ProcessHandle,
  [out, optional] PCLIENT_ID         ClientId,
  [in]            PKSTART_ROUTINE    StartRoutine,
  [in, optional]  PVOID              StartContext
);

我們使用PsCreateSystemThread函數開闢執行緒TcpListenWorker線上程內部執行如下流程啟動驅動伺服器端,由於我們自己封裝實現了標準介面組,所以使用起來幾乎與應用層無任何差異了。

  • CreateSocket 建立通訊端
  • Bind 繫結通訊端
  • Accept 等待接收請求
  • Receive 用於接收返回值
  • Send 用於傳送返回值
// 署名權
// right to sign one's name on a piece of work
// PowerBy: LyShark
// Email: [email protected]

#include "LySocket.hpp"

PETHREAD m_EThread = NULL;

// 執行緒函數
// PowerBy: LySHark
VOID TcpListenWorker(PVOID Context)
{
	WSK_SOCKET* paccept_socket = NULL;
	SOCKADDR_IN LocalAddress = { 0 };
	SOCKADDR_IN RemoteAddress = { 0 };
	NTSTATUS status = STATUS_UNSUCCESSFUL;

	// 建立通訊端
	PWSK_SOCKET TcpSocket = CreateSocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, WSK_FLAG_LISTEN_SOCKET);
	if (TcpSocket == NULL)
	{
		return;
	}

	// 設定繫結地址
	LocalAddress.sin_family = AF_INET;
	LocalAddress.sin_addr.s_addr = INADDR_ANY;
	LocalAddress.sin_port = HTON_SHORT(8888);

	status = Bind(TcpSocket, (PSOCKADDR)&LocalAddress);
	if (!NT_SUCCESS(status))
	{
		return;
	}

	// 迴圈接收
	while (1)
	{
		CHAR* read_buffer = (CHAR*)ExAllocatePoolWithTag(NonPagedPool, 2048, "read");
		paccept_socket = Accept(TcpSocket, (PSOCKADDR)&LocalAddress, (PSOCKADDR)&RemoteAddress);
		if (paccept_socket == NULL)
		{
			continue;
		}

		// 接收資料
		memset(read_buffer, 0, 2048);
		int read_len = Receive(paccept_socket, read_buffer, 2048, 0);
		if (read_len != 0)
		{
			DbgPrint("[核心A] => %s \n", read_buffer);

			// 傳送資料
			char send_buffer[2048] = "Hi, lyshark.com B";
			Send(paccept_socket, send_buffer, strlen(send_buffer), 0);

			// 接收確認包
			memset(read_buffer, 0, 2048);
			Receive(paccept_socket, read_buffer, 2, 0);
		}

		// 清理堆
		if (read_buffer != NULL)
		{
			ExFreePool(read_buffer);
		}

		// 關閉當前通訊端
		if (paccept_socket)
		{
			CloseSocket(paccept_socket);
		}
	}

	if (TcpSocket)
	{
		CloseSocket(TcpSocket);
	}
	PsTerminateSystemThread(STATUS_SUCCESS);
	return;
}

// 關閉通訊端
VOID UnDriver(PDRIVER_OBJECT driver)
{
	WSKCleanup();
	KeWaitForSingleObject(m_EThread, Executive, KernelMode, FALSE, NULL);
	if (m_EThread != NULL)
	{
		ObDereferenceObject(m_EThread);
	}
}

NTSTATUS DriverEntry(IN PDRIVER_OBJECT Driver, PUNICODE_STRING RegistryPath)
{
	DbgPrint("hello lyshark.com \n");

	// 初始化
	WSKStartup();

	HANDLE hThread = NULL;
	NTSTATUS status = STATUS_UNSUCCESSFUL;

	// 建立系統執行緒
	status = PsCreateSystemThread(&hThread, THREAD_ALL_ACCESS, NULL, NULL, NULL, TcpListenWorker, NULL);
	if (!NT_SUCCESS(status))
	{
		return status;
	}

	// 獲取執行緒EProcess結構
	status = ObReferenceObjectByHandle(hThread, THREAD_ALL_ACCESS, NULL, KernelMode, (PVOID*)&m_EThread, NULL);
	if (NT_SUCCESS(status) == FALSE)
	{
		return status;
	}

	ZwClose(hThread);
	Driver->DriverUnload = UnDriver;
	return STATUS_SUCCESS;
}

對於使用者端來說,只需要建立通訊端並連線到指定地址即可,這個過程大體上可以總結為如下;

  • CreateSocket 建立通訊端
  • Bind 繫結通訊端
  • Connect 連結伺服器端驅動
  • Send 傳送資料到伺服器端
  • Receive 接收資料到伺服器端
// 署名權
// right to sign one's name on a piece of work
// PowerBy: LyShark
// Email: [email protected]

#include "LySocket.hpp"

VOID UnDriver(PDRIVER_OBJECT driver)
{
	// 解除安裝並關閉Socket庫
	WSKCleanup();
}

NTSTATUS DriverEntry(IN PDRIVER_OBJECT Driver, PUNICODE_STRING RegistryPath)
{
	DbgPrint("hello lyshark.com \n");
	// 初始化
	WSKStartup();

	NTSTATUS      status = STATUS_SUCCESS;
	SOCKADDR_IN   LocalAddress = { 0, };
	SOCKADDR_IN   RemoteAddress = { 0, };

	// 建立通訊端
	PWSK_SOCKET TcpSocket = CreateSocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, WSK_FLAG_CONNECTION_SOCKET);
	if (TcpSocket == NULL)
	{
		Driver->DriverUnload = UnDriver;
		return STATUS_SUCCESS;
	}

	LocalAddress.sin_family = AF_INET;
	LocalAddress.sin_addr.s_addr = INADDR_ANY;
	status = Bind(TcpSocket, (PSOCKADDR)&LocalAddress);

	// 繫結失敗則關閉驅動
	if (!NT_SUCCESS(status))
	{
		CloseSocket(TcpSocket);

		Driver->DriverUnload = UnDriver;
		return STATUS_SUCCESS;
	}

	// 初始化伺服器端地址與埠資訊
	ULONG address[4] = { 127, 0, 0, 1 };

	RemoteAddress.sin_family = AF_INET;
	RemoteAddress.sin_addr.s_addr = change_uint(address[0], address[1], address[2], address[3]);
	RemoteAddress.sin_port = HTON_SHORT(8888);

	status = Connect(TcpSocket, (PSOCKADDR)&RemoteAddress);

	// 連線伺服器端,如果失敗則關閉驅動
	if (!NT_SUCCESS(status))
	{
		CloseSocket(TcpSocket);
		Driver->DriverUnload = UnDriver;
		return STATUS_SUCCESS;
	}

	// 傳送資料
	char send_buffer[2048] = "hello lyshark.com A";
	Send(TcpSocket, send_buffer, strlen(send_buffer), 0);

	// 接收資料
	CHAR* read_buffer = (CHAR*)ExAllocatePoolWithTag(NonPagedPool, 2048, "read");

	memset(read_buffer, 0, 1024);
	Receive(TcpSocket, read_buffer, 2048, 0);
	DbgPrint("[核心B] => %s \n", read_buffer);

	// 傳送確認包
	Send(TcpSocket, "ok", 2, 0);

	// 釋放記憶體
	ExFreePool(read_buffer);
	CloseSocket(TcpSocket);
	Driver->DriverUnload = UnDriver;
	return STATUS_SUCCESS;
}

編譯兩個驅動程式,首先執行server.sys驅動,執行後該驅動會在後臺等待使用者端連線,接著執行client.sys螢幕上可輸出如下提示,說明通訊已經建立了。