首页 > 其他分享 >驱动开发:内核封装TDI网络通信接口

驱动开发:内核封装TDI网络通信接口

时间:2022-11-03 09:57:03浏览次数:63  
标签:status TDI 封装 SUCCESS send return pTdiEndPointFileObject 通信接口

在上一篇文章《驱动开发:内核封装WSK网络通信接口》中,LyShark已经带大家看过了如何通过WSK接口实现套接字通信,但WSK实现的通信是内核与内核模块之间的,而如果需要内核与应用层之间通信则使用TDK会更好一些因为它更接近应用层,本章将使用TDK实现,TDI全称传输驱动接口,其主要负责连接Socket和协议驱动,用于实现访问传输层的功能,该接口比NDIS更接近于应用层,在早期Win系统中常用于实现过滤防火墙,同样经过封装后也可实现通信功能,本章将运用TDI接口实现驱动与应用层之间传输字符串,结构体,多线程收发等技术。

  • TDI传输字符串
  • TDI多线程收发
  • TDI传数结构实现认证

TDI 传输字符串: 服务端在应用层侦听,客户端是驱动程序,驱动程序加载后自动连接应用层并发送消息。

首先来看应用层(服务端)代码,具体我就不说了,来看教程的都是有基础的。

// 署名权
// right to sign one's name on a piece of work
// PowerBy: LyShark
// Email: [email protected]

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>  
#include <winsock2.h>  

#pragma comment(lib,"ws2_32.lib")
#define PORT 8888 

int main(int argc, char *argv[])
{
  printf("hello lyshark.com \n");
  WSADATA WSAData;
  SOCKET sock, msgsock;
  struct sockaddr_in ServerAddr;

  if (WSAStartup(MAKEWORD(2, 0), &WSAData) != SOCKET_ERROR)
  {
    ServerAddr.sin_family = AF_INET;
    ServerAddr.sin_port = htons(PORT);
    ServerAddr.sin_addr.s_addr = INADDR_ANY;

    sock = socket(AF_INET, SOCK_STREAM, 0);
    int BindRet = bind(sock, (LPSOCKADDR)&ServerAddr, sizeof(ServerAddr));
    int LinsRet = listen(sock, 10);
  }

  while (1)
  {
    char buf[1024] = { 0 };
    msgsock = accept(sock, (LPSOCKADDR)0, (int *)0);
    memset(buf, 0, sizeof(buf));

    recv(msgsock, buf, 1024, 0);
    printf("内核返回: %s \n", buf);

    char send_buffer[1024] = { 0 };
    memset(send_buffer, 0, 1024);
    strcpy(send_buffer, "Hi,R0 !");
    send(msgsock, send_buffer, strlen(send_buffer), 0);
    closesocket(msgsock);
  }
  closesocket(sock);
  WSACleanup();
  return 0;
}

再来是驱动层代码,如下所示;

// 署名权
// right to sign one's name on a piece of work
// PowerBy: LyShark
// Email: [email protected]

#include "MyTDI.hpp"

// 发送接收数据
NTSTATUS SendOnRecv()
{
  NTSTATUS status = STATUS_SUCCESS;
  HANDLE hTdiAddress = NULL;
  HANDLE hTdiEndPoint = NULL;
  PDEVICE_OBJECT pTdiAddressDevObj = NULL;
  PFILE_OBJECT pTdiEndPointFileObject = NULL;
  LONG pServerIp[4] = { 127, 0, 0, 1 };
  LONG lServerPort = 8888;
  UCHAR szSendData[] = "hello lyshark";
  ULONG ulSendDataLength = 1 + strlen(szSendData);
  HANDLE hThread = NULL;

  // TDI初始化
  status = TdiOpen(&pTdiAddressDevObj, &pTdiEndPointFileObject, &hTdiAddress, &hTdiEndPoint);
  if (!NT_SUCCESS(status))
  {
    return STATUS_SUCCESS;
  }

  // TDI TCP连接服务器
  status = TdiConnection(pTdiAddressDevObj, pTdiEndPointFileObject, pServerIp, lServerPort);
  if (!NT_SUCCESS(status))
  {
    return STATUS_SUCCESS;
  }

  // TDI TCP发送信息
  status = TdiSend(pTdiAddressDevObj, pTdiEndPointFileObject, szSendData, ulSendDataLength);
  if (!NT_SUCCESS(status))
  {
    return STATUS_SUCCESS;
  }
  DbgPrint("发送: %s\n", szSendData);

  // 创建接收信息多线程, 循环接收信息

  char szRecvData[1024] = { 0 };
  ULONG ulRecvDataLenngth = 1024;
  RtlZeroMemory(szRecvData, ulRecvDataLenngth);

  // TDI TCP接收信息
  do
  {
    ulRecvDataLenngth = TdiRecv(pTdiAddressDevObj, pTdiEndPointFileObject, szRecvData, ulRecvDataLenngth);
    if (0 < ulRecvDataLenngth)
    {
      DbgPrint("接收数据: %s\n", szRecvData);
      break;;
    }

  } while (TRUE);

  // 释放
  TdiClose(pTdiEndPointFileObject, hTdiAddress, hTdiEndPoint);
  return STATUS_SUCCESS;
}

VOID UnDriver(PDRIVER_OBJECT driver)
{
  DbgPrint("驱动卸载成功 \n");
}

NTSTATUS DriverEntry(IN PDRIVER_OBJECT Driver, PUNICODE_STRING RegistryPath)
{
  for (int x = 0; x < 10; x++)
  {
    SendOnRecv();
  }

  DbgPrint("驱动加载成功 \n");
  Driver->DriverUnload = UnDriver;
  return STATUS_SUCCESS;
}

首先运行应用层开启服务端侦听,然后运行驱动程序,会输出如下信息;

TDI 多线程收发包: 实现驱动内部发送数据包后开启一个线程用于等待应用层返回并输出结果,多线程收发在发送数据包后需要创建新的线程等待接收。

首先是服务端代码。

// 署名权
// right to sign one's name on a piece of work
// PowerBy: LyShark
// Email: [email protected]

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>  
#include <winsock2.h>  

#pragma comment(lib,"ws2_32.lib")
#define PORT 8888 

int main(int argc, char *argv[])
{
	printf("hello lyshark.com \n");
	WSADATA WSAData;
	SOCKET sock, msgsock;
	struct sockaddr_in ServerAddr;

	if (WSAStartup(MAKEWORD(2, 0), &WSAData) != SOCKET_ERROR)
	{
		ServerAddr.sin_family = AF_INET;
		ServerAddr.sin_port = htons(PORT);
		ServerAddr.sin_addr.s_addr = INADDR_ANY;

		sock = socket(AF_INET, SOCK_STREAM, 0);
		int BindRet = bind(sock, (LPSOCKADDR)&ServerAddr, sizeof(ServerAddr));
		int LinsRet = listen(sock, 10);
	}

	while (1)
	{
		char buf[1024] = { 0 };
		msgsock = accept(sock, (LPSOCKADDR)0, (int *)0);
		memset(buf, 0, sizeof(buf));

		recv(msgsock, buf, 1024, 0);
		printf("内核返回: %s \n", buf);

		char send_buffer[1024] = { 0 };
		memset(send_buffer, 0, 1024);
		strcpy(send_buffer, "Hi,R0 !");
		send(msgsock, send_buffer, strlen(send_buffer), 0);
		closesocket(msgsock);
	}
	closesocket(sock);
	WSACleanup();
	return 0;
}

驱动程序代码如下,RecvThreadProc主要负责数据接收,SendThreadData负责数据发送。

// 署名权
// right to sign one's name on a piece of work
// PowerBy: LyShark
// Email: [email protected]

#include "LySocket.hpp"

typedef struct _MY_DATA
{
	PDEVICE_OBJECT pTdiAddressDevObj;
	PFILE_OBJECT pTdiEndPointFileObject;
	HANDLE hTdiAddress;
	HANDLE hTdiEndPoint;
}MY_DATA, *PMY_DATA;

// 接收信息多线程
VOID RecvThreadProc(_In_ PVOID StartContext)
{
	PMY_DATA pMyData = (PMY_DATA)StartContext;
	NTSTATUS status = STATUS_SUCCESS;
	char szRecvData[1024] = { 0 };
	ULONG ulRecvDataLenngth = 1024;
	RtlZeroMemory(szRecvData, ulRecvDataLenngth);

	// TDI TCP接收信息
	do
	{
		ulRecvDataLenngth = TdiRecv(pMyData->pTdiAddressDevObj, pMyData->pTdiEndPointFileObject, szRecvData, ulRecvDataLenngth);
		if (0 < ulRecvDataLenngth)
		{
			DbgPrint("线程句柄:%x --> 接收数据包: %s\n", pMyData->hTdiEndPoint, szRecvData);
			break;;
		}

	} while (TRUE);

	// 释放
	TdiClose(pMyData->pTdiEndPointFileObject, pMyData->hTdiAddress, pMyData->hTdiEndPoint);
	ExFreePool(pMyData);
}

// 多线程发送
NTSTATUS SendThreadData()
{
	NTSTATUS status = STATUS_SUCCESS;
	HANDLE hTdiAddress = NULL;
	HANDLE hTdiEndPoint = NULL;
	PDEVICE_OBJECT pTdiAddressDevObj = NULL;
	PFILE_OBJECT pTdiEndPointFileObject = NULL;
	LONG pServerIp[4] = { 127, 0, 0, 1 };
	LONG lServerPort = 8888;
	UCHAR szSendData[] = "hello lyshark";
	ULONG ulSendDataLength = 1 + strlen(szSendData);
	HANDLE hThread = NULL;

	// TDI初始化
	status = TdiOpen(&pTdiAddressDevObj, &pTdiEndPointFileObject, &hTdiAddress, &hTdiEndPoint);
	if (!NT_SUCCESS(status))
	{
		return STATUS_SUCCESS;
	}

	// TDI TCP连接服务器
	status = TdiConnection(pTdiAddressDevObj, pTdiEndPointFileObject, pServerIp, lServerPort);
	if (!NT_SUCCESS(status))
	{
		return STATUS_SUCCESS;
	}

	// TDI TCP发送信息
	status = TdiSend(pTdiAddressDevObj, pTdiEndPointFileObject, szSendData, ulSendDataLength);
	if (!NT_SUCCESS(status))
	{
		return STATUS_SUCCESS;
	}
	DbgPrint("发送 %s\n", szSendData);

	// 创建接收信息多线程, 循环接收信息
	PMY_DATA pMyData = ExAllocatePool(NonPagedPool, sizeof(MY_DATA));
	pMyData->pTdiAddressDevObj = pTdiAddressDevObj;
	pMyData->pTdiEndPointFileObject = pTdiEndPointFileObject;
	pMyData->hTdiAddress = hTdiAddress;
	pMyData->hTdiEndPoint = hTdiEndPoint;

	PsCreateSystemThread(&hThread, 0, NULL, NtCurrentProcess(), NULL, RecvThreadProc, pMyData);
}

VOID UnDriver(PDRIVER_OBJECT driver)
{
	DbgPrint("驱动卸载成功 \n");
}

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

	for (int x = 0; x < 10; x++)
	{
		SendThreadData();
	}
	Driver->DriverUnload = UnDriver;
	return STATUS_SUCCESS;
}

运行应用层服务端等待侦听,运行驱动程序输出如下效果;

TDI 传数结构实现认证: 驱动内部发送结构体给应用层,应用层验证结构体成员,此功能可实现对驱动程序的控制机制,例如是否允许驱动加载卸载等,通常用于驱动辅助认证。

应用层代码

// 署名权
// right to sign one's name on a piece of work
// PowerBy: LyShark
// Email: [email protected]

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>  
#include <winsock2.h>  

#pragma comment(lib,"ws2_32.lib")
#define PORT 8888

// 传输结构体
typedef struct
{
	int uuid;
	char username[256];
	char password[256];
}SocketData;

int main(int argc, char *argv[])
{
	printf("hello lyshark.com \n");

	WSADATA WSAData;
	SOCKET sock, msgsock;
	struct sockaddr_in ServerAddr;

	if (WSAStartup(MAKEWORD(2, 0), &WSAData) != SOCKET_ERROR)
	{
		ServerAddr.sin_family = AF_INET;
		ServerAddr.sin_port = htons(PORT);
		ServerAddr.sin_addr.s_addr = INADDR_ANY;

		sock = socket(AF_INET, SOCK_STREAM, 0);
		int BindRet = bind(sock, (LPSOCKADDR)&ServerAddr, sizeof(ServerAddr));
		int LinsRet = listen(sock, 10);
	}

	while (1)
	{
		char buf[8192] = { 0 };
		msgsock = accept(sock, (LPSOCKADDR)0, (int *)0);
		memset(buf, 0, sizeof(buf));

		// 接收返回数据
		recv(msgsock, buf, sizeof(SocketData), 0);

		// 强转结构体
		SocketData* msg = (SocketData*)buf;

		printf("UUID = %d \n", msg->uuid);
		printf("名字 = %s \n", msg->username);
		printf("密码 = %s \n", msg->password);

		// 验证通过则继续使用
		if ((strcmp(msg->username, "lyshark") == 0) && (strcmp(msg->password, "123") == 0))
		{
			char send_buffer[8192] = { 0 };
			memset(send_buffer, 0, 8192);
			strcpy(send_buffer, "success");
			send(msgsock, send_buffer, strlen(send_buffer), 0);
			closesocket(msgsock);
		}
		// 不通过则禁止驱动加载
		else
		{
			char send_buffer[8192] = { 0 };
			memset(send_buffer, 0, 8192);
			strcpy(send_buffer, "error");
			send(msgsock, send_buffer, strlen(send_buffer), 0);
			closesocket(msgsock);
		}
	}
	closesocket(sock);
	WSACleanup();
	return 0;
}

驱动层代码

// 署名权
// right to sign one's name on a piece of work
// PowerBy: LyShark
// Email: [email protected]
#include "LySocket.hpp"

// 传输结构体
typedef struct
{
	int uuid;
	char username[256];
	char password[256];
}SocketData;

// 验证账号密码是否正确
BOOLEAN CheckDriver()
{
	NTSTATUS status = STATUS_SUCCESS;
	HANDLE hTdiAddress = NULL;
	HANDLE hTdiEndPoint = NULL;
	PDEVICE_OBJECT pTdiAddressDevObj = NULL;
	PFILE_OBJECT pTdiEndPointFileObject = NULL;
	LONG pServerIp[4] = { 127, 0, 0, 1 };
	LONG lServerPort = 8888;

	// TDI初始化
	status = TdiOpen(&pTdiAddressDevObj, &pTdiEndPointFileObject, &hTdiAddress, &hTdiEndPoint);
	if (!NT_SUCCESS(status))
	{
		return STATUS_SUCCESS;
	}

	// TDI TCP连接服务器
	status = TdiConnection(pTdiAddressDevObj, pTdiEndPointFileObject, pServerIp, lServerPort);
	if (!NT_SUCCESS(status))
	{
		return STATUS_SUCCESS;
	}

	SocketData ptr;

	RtlZeroMemory(&ptr, sizeof(SocketData));

	// 填充结构
	ptr.uuid = 1001;
	RtlCopyMemory(ptr.username, "lyshark", strlen("xxxxxxx"));
	RtlCopyMemory(ptr.password, "123123", strlen("xxxxxx"));

	// TDI TCP发送信息
	status = TdiSend(pTdiAddressDevObj, pTdiEndPointFileObject, &ptr, sizeof(SocketData));
	if (!NT_SUCCESS(status))
	{
		return STATUS_SUCCESS;
	}

	// 创建接收信息多线程, 循环接收信息
	char szRecvData[8192] = { 0 };
	ULONG ulRecvDataLenngth = 8192;
	RtlZeroMemory(szRecvData, ulRecvDataLenngth);

	// TDI TCP接收信息
	do
	{
		ulRecvDataLenngth = TdiRecv(pTdiAddressDevObj, pTdiEndPointFileObject, szRecvData, ulRecvDataLenngth);
		if (0 < ulRecvDataLenngth)
		{
			DbgPrint("接收数据: %s\n", szRecvData);

			if (strncmp(szRecvData, "success", 7) == 0)
			{
				// 释放
				TdiClose(pTdiEndPointFileObject, hTdiAddress, hTdiEndPoint);
				return TRUE;
			}
			else if (strncmp(szRecvData, "error", 5) == 0)
			{
				// 释放
				TdiClose(pTdiEndPointFileObject, hTdiAddress, hTdiEndPoint);
				return FALSE;
			}
			break;;
		}
	} while (TRUE);

	// 释放
	TdiClose(pTdiEndPointFileObject, hTdiAddress, hTdiEndPoint);
	return STATUS_SUCCESS;
}

VOID UnDriver(PDRIVER_OBJECT driver)
{
	DbgPrint("驱动卸载成功 \n");
}

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

	BOOLEAN ref = CheckDriver();

	if (ref == FALSE)
	{
		DbgPrint("[LyShark.com] 驱动已过期,无法加载 \n");
		Driver->DriverUnload = UnDriver;
		return STATUS_SUCCESS;
	}

	DbgPrint("[*] 驱动正常使用 \n");
	Driver->DriverUnload = UnDriver;
	return STATUS_SUCCESS;
}

运行应用层服务端,并运行驱动程序,则会验证该驱动是否合法,如果合法则加载不合法则拒绝;

标签:status,TDI,封装,SUCCESS,send,return,pTdiEndPointFileObject,通信接口
From: https://www.cnblogs.com/LyShark/p/16851278.html

相关文章

  • 驱动开发:内核封装WSK网络通信接口
    本章LyShark将带大家学习如何在内核中使用标准的Socket套接字通信接口,我们都知道Windows应用层下可直接调用WinSocket来实现网络通信,但在内核模式下应用层API接口无法使用,......
  • 兄弟组件传参_bus封装
    vue3Bus兄弟组件传参typeBusClass={emit:(name:string)=>voidon:(name:string,callBack:Function)=>void}typeParamsKey=string|number|sy......
  • 【Android】Android开发之Activity的管理类,结束关闭指定的Activity,单例模式封装
    作者:程序员小冰,GitHub主页:​​https://github.com/QQ986945193​​​新浪微博:​​​http://weibo.com/mcxiaobing​​长期维护的Android项目,里面包括常用功能实现,以及知识......
  • 后台response和异常处理封装
    我们自己封装的一些东西,往往放在一个utils文件夹内,以后也方便管理和导入后台response封装#自己封装的Response对象fromrest_framework.responseimportResponse......
  • JSONP的原理和封装
    jsonp是一种跨域通信的手段,它的原理其实很简单:首先是利用script标签的src属性来实现跨域。通过将前端方法作为参数传递到服务器端,然后由服务器端注入参数之后再返回,实现......
  • ElementUI 图片文件预览插件封装
    ImgViewer.vue<template><Dialogtitle="图片预览":visible.sync="dialogVisible":append-to-body="true"@closed="dialogImageUrl=''"><imgv-if="dialogI......
  • C++语言从入门到精通——封装
    C语言封装都可以访问,且不需要权限认证////CreatedbyCWFon2022/10/5.//#include<stdio.h>#include<string.h>#include<stdlib.h>structPerson{charname[64];in......
  • c++从入门到精通——数组类封装以及操作符重载
    #include"myArray.h"MyArray::MyArray(){//cout<<"默认构造函数调用"<<endl;this->m_Capacity=100;this->m_Size=0;this->pAddress=newint[this->m_Cap......
  • ASEMI肖特基二极管SS210L参数,SS210L规格,SS210L封装
    编辑-ZASEMI肖特基二极管SS210L参数:型号:SS210L最大重复峰值反向电压(VRRM):100V最大RMS电桥输入电压(VRMS):70V最大直流阻断电压(VDC):100V最大平均正向整流输出电流(IF):2.0A峰值正向浪......
  • ASEMI肖特基二极管SS210L参数,SS210L规格,SS210L封装
    编辑-ZASEMI肖特基二极管SS210L参数:型号:SS210L最大重复峰值反向电压(VRRM):100V最大RMS电桥输入电压(VRMS):70V最大直流阻断电压(VDC):100V最大平均正向整流输出电流(IF):2.0A峰......