(C/Windows) 无法卸载驱动程序

(C/Windows) Unable to unload driver

我的 OP 是 Windows 7 64 位。我正在加载一个带有 DSEfix 的驱动程序(绕过 Windows 的驱动程序签名强制执行)并且工作正常。 IOCTL 请求按照应有的方式执行,但每当我尝试卸载我的驱动程序时,它都会失败:ControlService(hService, SERVICE_CONTROL_STOP, &ss,错误代码为无效句柄。

这是我的驱动程序条目:

NTSTATUS DriverEntry(PDRIVER_OBJECT Object, PUNICODE_STRING RegistryPath) {

UNICODE_STRING dNUS = { 0 };
RtlInitUnicodeString(&dNUS, L"\Device\testdriver");

UNICODE_STRING dSLU = { 0 };
RtlInitUnicodeString(&dSLU, L"\DosDevices\testdriver");

IoCreateDevice(Object, 0, &dNUS, FILE_DEVICE_UNKNOWN, FILE_DEVICE_SECURE_OPEN, FALSE, &deviceObj);
IoCreateSymbolicLink(&dSLU, &dNUS);

Object->MajorFunction[IRP_MJ_CREATE] = CCreate;
Object->MajorFunction[IRP_MJ_CLOSE] = CClose;
Object->MajorFunction[IRP_MJ_DEVICE_CONTROL] = IOCTL;
Object->DriverUnload = Unload;

return(STATUS_SUCCESS);

和卸载函数:

NTSTATUS Unload(PDRIVER_OBJECT Object) {
UNICODE_STRING symLink;
RtlInitUnicodeString(&symLink, L"\DosDevices\testdriver");

if (Object->DeviceObject != NULL)
{
    IoDeleteSymbolicLink(&symLink);
    IoDeleteDevice(Object->DeviceObject);
}

在用户模式方面,当从 CreateServiceA 加载驱动程序和 hService 时,我从 OpenSCManagerA(NULL, NULL, SC_MANAGER_CREATE_SERVICE) 获取 hSCManager。两者都有效并且可以很好地加载驱动程序。

这是我在用户模式下的卸载驱动程序函数:

bool UnloadDriver()
{
if (!hSCManager) return false;
if (!hService) return false;

cout << "STOPPING DRIVER" << endl;

SERVICE_STATUS ss;
if (ControlService(hService, SERVICE_CONTROL_STOP, &ss))
{
    if (ss.dwCurrentState == SERVICE_STOPPED)
    {
        DeleteService(hService);
        CloseServiceHandle(hSCManager);
        CloseServiceHandle(hService);
        cout << "DRIVER UNLOADED" << endl;
        return true;
    }
    else
    {
        cout << "SERVICE NOT STOPPED IN TIME" << endl;
        CloseServiceHandle(hSCManager);
        CloseServiceHandle(hService);
        return false;
    }
}
else
{
    cout << "SERVICE_CONTROL_STOP FAILED" << endl;
    CloseServiceHandle(hSCManager);
    CloseServiceHandle(hService);
    return false;
}

好吧,正如 RbMm 所说,我忽略了注册表项的删除...好吧,但是在我移动了那段代码之后,我仍然无法卸载我的驱动程序。

于是我发现CreateService获取的SC_HANDLE是无效的。尽管它在 MSDN 上说可以从 CreateService 使用句柄,但它对我不起作用(可能是 DSE)。相反,您应该只创建一个新的 SCManager 和一个新的 SCService,这样您就可以开始了。现在 ControlService 为我返回 true :)