开发环境
pyside6+pywin32搭建桌面环境
整体框架
import os.path
import sys
from ui import Ui_Form
from PySide6.QtWidgets import QApplication, QWidget
from PySide6.QtCore import Slot
import win32service
import win32api
import win32file
import winerror
from winioctlcon import CTL_CODE,FILE_DEVICE_UNKNOWN, METHOD_BUFFERED, FILE_ANY_ACCESS
import ctypes
DriverName = "\\DEVICE\\CHYDriver"
SymbolicLink = "\\??\\CHYDriver"
DriverSimpleName = "CHYDriver"
DriverFileName = "Sample.sys"
WriteData = CTL_CODE(FILE_DEVICE_UNKNOWN,0x803,METHOD_BUFFERED,FILE_ANY_ACCESS)
ReadData = CTL_CODE(FILE_DEVICE_UNKNOWN,0x804,METHOD_BUFFERED,FILE_ANY_ACCESS)
ReadWriteData = CTL_CODE(FILE_DEVICE_UNKNOWN,0x805,METHOD_BUFFERED,FILE_ANY_ACCESS)
class MyWidget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
Ui_Form().setupUi(self)
self.service_sys_handle = None
self.service_manager_handle = None
def get_errorno(self, info):
error_code = win32api.GetLastError()
if error_code != 0:
print(info + '失败 status', error_code)
else:
print(info + '成功')
if __name__ == "__main__":
app = QApplication(sys.argv)
myWindow = MyWidget()
myWindow.show()
sys.exit(app.exec())
加载驱动
步骤
1、OpenSCManager打开服务控制管理器
2、CreateService为驱动创建对应服务(此时不需要调用OpenService打开服务)
3、驱动服务已经存在则用OpenService打开服务
4、StartService加载启动驱动服务
5、用CloseServiceHandle关闭释放句柄
# 驱动名和驱动文件的全路径
def load_driver(self, driver_name, driver_path):
# 1、OpenSCManager打开服务控制管理器
try:
self.service_manager_handle = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS)
except Exception as e:
print(e)
self.get_errorno('打开服务控制管理器')
# 2、CreateService为驱动创建对应服务(此时不需要调用OpenService打开服务)
print(driver_path)
if not os.path.isfile(driver_path):
print("The file does not exist at the specified path.")
try:
self.service_sys_handle = win32service.CreateService(self.service_manager_handle,
driver_name,
driver_name,
win32service.SERVICE_START,
win32service.SERVICE_KERNEL_DRIVER,
win32service.SERVICE_DEMAND_START,
win32service.SERVICE_ERROR_NORMAL,
driver_path,
None,
0,
None,
None,
None)
except Exception as e:
print(e)
error_code = win32api.GetLastError()
if error_code == winerror.ERROR_SERVICE_EXISTS: # 服务已经存在
# 3、驱动服务已经存在则用OpenService打开服务
try:
self.service_sys_handle = win32service.OpenService(self.service_manager_handle, driver_name, win32service.SERVICE_ALL_ACCESS)
except Exception as e:
print(e)
self.get_errorno('打开服务')
elif error_code == 0:
print('创建服务并打开成功')
else:
print('创建服务失败 status', error_code)
# 4、StartService加载启动驱动服务
try:
win32service.StartService(self.service_sys_handle, None)
except Exception as e:
print(e)
self.get_errorno('启动服务')
# 5、用CloseServiceHandle关闭释放句柄
if self.service_manager_handle:
win32service.CloseServiceHandle(self.service_manager_handle)
if self.service_sys_handle:
win32service.CloseServiceHandle(self.service_sys_handle)
@Slot()
def on_loaddriver_clicked(self):
print('进入加载驱动')
print('驱动名', DriverSimpleName)
print('驱动全路径', os.path.abspath(DriverFileName))
self.load_driver(DriverSimpleName, os.path.abspath(DriverFileName))
print('退出加载驱动')
卸载驱动
步骤
1、OpenSCManager打开服务控制管理器
2、用OpenService打开服务
3、用ControlService停止服务
4、删除驱动对应服务DeleteService
5、用CloseServiceHandle关闭释放句柄
def unload_driver(self, driver_name):
# 1、OpenSCManager打开服务控制管理器
try:
self.service_manager_handle = win32service.OpenSCManager(None,None,win32service.SC_MANAGER_ALL_ACCESS)
except Exception as e:
print(e)
self.get_errorno('打开服务控制管理器')
# 2、用OpenService打开服务
try:
self.service_sys_handle = win32service.OpenService(self.service_manager_handle, driver_name, win32service.SERVICE_ALL_ACCESS)
except Exception as e:
print(e)
self.get_errorno('打开服务')
"""
typedef struct _SERVICE_STATUS { // ss
DWORD dwServiceType;
DWORD dwCurrentState;
DWORD dwControlsAccepted;
DWORD dwWin32ExitCode;
DWORD dwServiceSpecificExitCode;
DWORD dwCheckPoint;
DWORD dwWaitHint;
}
"""
# 第一个即是传入的win32service.SERVICE_KERNEL_DRIVER
# 3、用ControlService停止服务
try:
status = win32service.ControlService(self.service_sys_handle, win32service.SERVICE_CONTROL_STOP)
if status[1] != win32service.SERVICE_STOPPED:
error_code = win32api.GetLastError()
print('停止服务失败 status', error_code)
else:
print('停止服务成功')
except Exception as e:
print(e)
# 4、删除驱动对应服务
try:
# 无返回值
win32service.DeleteService(self.service_sys_handle)
except Exception as e:
print(e)
print('删除服务成功')
# 5、用CloseServiceHandle关闭释放句柄
if self.service_manager_handle:
win32service.CloseServiceHandle(self.service_manager_handle)
if self.service_sys_handle:
win32service.CloseServiceHandle(self.service_sys_handle)
@Slot()
def on_unloaddriver_clicked(self):
print('进入卸载驱动')
self.unload_driver(DriverSimpleName)
print('退出卸载驱动')
打开驱动设备
1、CreateFile打开驱动设备
@Slot()
def on_opendriverdevice_clicked(self):
print('进入打开驱动设备')
# IRP_MJ_CREATE
self.device_handle = win32file.CreateFile(SymbolicLink, win32file.GENERIC_READ | win32file.GENERIC_WRITE, win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, None, win32file.OPEN_EXISTING, win32file.FILE_ATTRIBUTE_NORMAL, None)
print(self.device_handle)
error_code = win32api.GetLastError()
if error_code!=0:
print('打开驱动设备失败 status', error_code)
else:
print('打开驱动设备成功')
print('退出打开驱动设备')
关闭驱动设备
1、CloseHandle关闭驱动设备
@Slot()
def on_closedriverdevice_clicked(self):
print('进入关闭驱动设备')
# IRP_MJ_CLOSE
win32file.CloseHandle(self.device_handle)
error_code = win32api.GetLastError()
if error_code!=0:
print('关闭驱动设备失败 status', error_code)
else:
print('关闭驱动设备成功')
print('退出关闭驱动设备')
写数据
DeviceIoControl
@Slot()
def on_write_clicked(self):
print('进入写数据')
data = "Hello World Write 你好\0".encode('gbk')
print('写数据', data)
# 写入数据返回None
win32file.DeviceIoControl(self.device_handle, WriteData, data, None)
self.get_errorno('写数据')
print('退出写数据')
WriteFile
@Slot()
def on_mjwrite_clicked(self):
print('进入写数据')
data = "Hello World Write 你好\0".encode('gbk')
print('写数据', data)
# 写入数据返回None
win32file.WriteFile(self.device_handle, data)
self.get_errorno('写数据')
print('退出写数据')
读数据
DeviceIoControl
@Slot()
def on_read_clicked(self):
print('进入读数据')
output = win32file.DeviceIoControl(self.device_handle, ReadData, None, 1024)
print('读取数据', output[:-1].decode('gbk'))
print('退出读数据')
ReadFile
@Slot()
def on_mjread_clicked(self):
print('进入读数据')
(code ,output) = win32file.ReadFile(self.device_handle, 1024)
print('读取数据', output[:-1].decode('gbk'))
print('退出读数据')
读写数据
DeviceIoControl
@Slot()
def on_readwrite_clicked(self):
print('进入读写数据')
param1 = 10
param2 = 20
data = param1.to_bytes(4, byteorder='little') + param2.to_bytes(4, byteorder='little')
print('发送数据:' , param1, param2)
output = win32file.DeviceIoControl(self.device_handle, ReadWriteData, data, 1024, None)
print('读取数据', int.from_bytes(output, 'little'))
print('退出读写数据')
保护指定PID的进程
@Slot()
def on_addproject_clicked(self):
pid = int(self.ui.pid.text())
data = pid.to_bytes(4, byteorder='little')
win32file.DeviceIoControl(self.device_handle, AddProject, data, None)
self.get_errorno('添加保护pid ' + str(pid))
@Slot()
def on_removeproject_clicked(self):
pid = int(self.ui.pid.text())
data = pid.to_bytes(4, byteorder='little')
win32file.DeviceIoControl(self.device_handle, RemoveProject, data, None)
self.get_errorno('移除保护pid '+ str(pid))
突破保护进程跨进程读内存
@Slot()
def on_readmemory_clicked(self):
class Info(ctypes.Structure):
_fields_ = [("pid", ctypes.c_uint32), ("address", ctypes.c_void_p), ("length", ctypes.c_uint32)]
info = Info()
info.pid = int(self.ui.pid.text())
info.address = eval(self.ui.address.text())
info.length = int(self.ui.length.text())
data = ctypes.string_at(ctypes.addressof(info), ctypes.sizeof(info))
memdata = win32file.DeviceIoControl(self.device_handle, ReadProcessMemory, data, 1024)
self.get_errorno('读取内存 pid '+ str(info.pid))
print(int.from_bytes(memdata, byteorder='little'))
突破保护进程跨进程写内存(只读内存也可)
@Slot()
def on_writememory_clicked(self):
class Info(ctypes.Structure):
_fields_ = [("pid", ctypes.c_uint32), ("address", ctypes.c_void_p), ("r3address", ctypes.c_void_p), ("length", ctypes.c_uint32)]
info = Info()
info.pid = int(self.ui.pid.text())
info.address = eval(self.ui.address.text())
info.length = int(self.ui.length.text())
value = int(self.ui.value.text())
c_value = ctypes.c_int(value)
print(ctypes.addressof(c_value))
info.r3address = ctypes.addressof(c_value)
data = ctypes.string_at(ctypes.addressof(info), ctypes.sizeof(info))
win32file.DeviceIoControl(self.device_handle, WriteProcessMemory, data, None)
self.get_errorno('写入内存 pid '+ str(info.pid))