Controlservice ошибка 1052

In previous post, I’ve shared how to stop “STOPPABLE” windows service via command line.

An example of STOPPABLE” windows service is “themes”

C:\>sc query themes

SERVICE_NAME: themes

TYPE               : 20  WIN32_SHARE_PROCESS

STATE              : 4  RUNNING

(STOPPABLE,NOT_PAUSABLE,ACCEPTS_SHUTDOWN)

WIN32_EXIT_CODE    : 0  (0x0)

SERVICE_EXIT_CODE  : 0  (0x0)

CHECKPOINT         : 0x0

WAIT_HINT          : 0x0

C:\>

What if the service is “NOT_STOPPABLE”?

An example of STOPPABLE” windows service is “TermService” (Terminal Services)

C:\>sc query termservice

SERVICE_NAME: termservice

TYPE               : 20  WIN32_SHARE_PROCESS

STATE              : 4  RUNNING

(NOT_STOPPABLE,NOT_PAUSABLE,IGNORES_SHUTDOWN)

WIN32_EXIT_CODE    : 0  (0x0)

SERVICE_EXIT_CODE  : 0  (0x0)

CHECKPOINT         : 0x0

WAIT_HINT          : 0x0

C:\>

C:\>sc stop TermService
[SC] ControlService FAILED 1052:

The requested control is not valid for this service.
C:\>

C:\>net stop TermService
The requested pause or stop is not valid for this service.

More help is available by typing NET HELPMSG 2191.
C:\>

I’ve found a very good blog here and leave a comment there.

https://www.netspi.com/blog/entryid/116/penetration-testing-stopping-an-unstoppable-windows-service

Hopefully, someone will assist me on this issue.

FirewallEngineer said on 11/22/2013:

Hi, I would appreciate if you could share how to stop the TermService via command line.

C:\>sc query | findstr -i term
SERVICE_NAME: TermService
DISPLAY_NAME: Terminal Services

C:\>
C:\>sc qc TermService
[SC] GetServiceConfig SUCCESS

SERVICE_NAME: TermService
TYPE : 20 WIN32_SHARE_PROCESS
START_TYPE : 3 DEMAND_START
ERROR_CONTROL : 1 NORMAL
BINARY_PATH_NAME : C:\WINDOWS\System32\svchost -k DComLaunch
LOAD_ORDER_GROUP :
TAG : 0
DISPLAY_NAME : Terminal Services
DEPENDENCIES : RPCSS
SERVICE_START_NAME : LocalSystem

C:\>
C:\>tasklist | find /i “svchost”
svchost.exe 880 Console 0 4,564 K
svchost.exe 968 Console 0 3,976 K
svchost.exe 1060 Console 0 20,716 K
svchost.exe 1116 Console 0 2,760 K
svchost.exe 1184 Console 0 4,192 K

C:\>

This comment will not appear until it is approved.

REFERENCE:

http://bartdesmet.net/blogs/bart/archive/2004/10/16/438.aspx

https://www.netspi.com/blog/entryid/116/penetration-testing-stopping-an-unstoppable-windows-service

  • Remove From My Forums
  • Question

  • Hello.

    I have a USB Host Controller  upper filter driver that I install via CreateService(). It is running, it does not appear in Service Control Manager, it appears in sc query type= drivers. It is reported as KERNEL_DRIVER, RUNNING, (STOPPABLE,NOT_PAUSABLE,IGNORES_SHUTDOWN).

    How exactly can I stop my driver?

    sc stop MyDriver returns ControlService FAILED 1052: (The requested control is not valid for this service).

    ControlService(ServiceHandle,SERVICE_CONTROL_STOP,&ServiceStatus)) fails in code with 1052 also (As Administrator).

    1.) I am beginning to believe that I am unable to stop the driver due to the way I am installing it (via CreateService()). It there is no way to stop the service / driver in this scenario then I will try installting via the .inf/setup route.

    Am I correct? Is so is there any documentation anywhere covering this?

    Thanks.

Answers

  • if this is a device upper filter (not a class upper filter), you should use an INF to install it. Regardless of inf/CreateService, you can’t use the SCM start/stop service calls to control the state of a pnp driver, unlike a legacy non pnp driver which can
    be unloaded/loaded with these APIs. a pnp driver can only be stopped and unloaded when all pnp stacks referencing it are unloaded. this means using devcon or device manager to disable all instances so that the driver unloads.

    why do you need to filter the USB HC?


    d — This posting is provided «AS IS» with no warranties, and confers no rights.

    • Marked as answer by

      Wednesday, March 5, 2014 5:31 PM

Hi All,
We are having a Windows
Service developed with Visual C++ (VS 2012), and we applied ‘Protection’ for this service (Aim is to prevent Kill process/Stop service from any other method). For applying protection into our service, we are editing the ‘EXPLICIT_ACCESS’ and ‘SECURITY_DESCRIPTOR’.

But we can kill process/stop
service using ‘psexec’ command even if the protection is enabled. So kindly help me to solve this issue, here is the sample code we used for applying for protection:

—————————————-

BOOL SetServicePrivilege(long lUser, long lProtectService)
{
SECURITY_DESCRIPTOR sd;
LPTSTR lpszUser;
EXPLICIT_ACCESS eaPowUser;
PSID pAdminSID = NULL;
DWORD dwAccessPermissions = 0,dwError = 0,dwSize = 0;
PACL pacl = NULL,pNewAcl = NULL;
SC_HANDLE schManager = NULL,schService = NULL;
PSECURITY_DESCRIPTOR psd = NULL;
BOOL bDaclPresent = FALSE,bDaclDefaulted = FALSE,bSuccess = FALSE,bRelease = FALSE;
////////////////////////////////////////////////////////////////////////////////////
try
{
if(lUser == 1)
{
lpszUser = "Power Users";
if(lProtectService == 0)
{
dwAccessPermissions = SERVICE_ENUMERATE_DEPENDENTS | SERVICE_INTERROGATE |
SERVICE_PAUSE_CONTINUE | SERVICE_QUERY_CONFIG |
SERVICE_QUERY_STATUS | SERVICE_START | SERVICE_STOP |
SERVICE_USER_DEFINED_CONTROL | READ_CONTROL;
}
else
{
dwAccessPermissions = SERVICE_START | READ_CONTROL | DELETE;
}
}
else if(lUser == 2)
{
lpszUser = "Administrators";
if(lProtectService == 0)
{
dwAccessPermissions = SERVICE_CHANGE_CONFIG | SERVICE_ENUMERATE_DEPENDENTS |
SERVICE_INTERROGATE | SERVICE_PAUSE_CONTINUE |
SERVICE_QUERY_CONFIG | SERVICE_QUERY_STATUS | SERVICE_START |
SERVICE_STOP | SERVICE_USER_DEFINED_CONTROL | READ_CONTROL |
WRITE_OWNER | WRITE_DAC | DELETE ;
}
else
{
dwAccessPermissions = SERVICE_START | READ_CONTROL | DELETE;
}
}
else
{
goto cleanup;
}
schManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);// Obtain a handle to the Service Controller.
if(schManager == NULL)
{
goto cleanup;
}
schService = OpenService(schManager, "TestService", READ_CONTROL | WRITE_DAC);// Obtain a handle to the service.
if(schService == NULL)
{
goto cleanup;
}
psd = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
if(!QueryServiceObjectSecurity(schService, DACL_SECURITY_INFORMATION, psd, 0, &dwSize))// Get the current security descriptor.
{
long lError = GetLastError();
if(lError == ERROR_INSUFFICIENT_BUFFER)
{
psd = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR, dwSize);
if(psd == NULL)
{
goto cleanup;
}
else
{
bRelease = TRUE;
}
///////////////////
if(!QueryServiceObjectSecurity(schService, DACL_SECURITY_INFORMATION, psd, dwSize, &dwSize))
{
goto cleanup;
}
}
else
{
goto cleanup;
}
}
if(!GetSecurityDescriptorDacl(psd, &bDaclPresent, &pacl, &bDaclDefaulted))// Get the DACL.
{
goto cleanup;
}
SID_IDENTIFIER_AUTHORITY SIDAuthNT = SECURITY_NT_AUTHORITY;
if(!AllocateAndInitializeSid(&SIDAuthNT, 2,SECURITY_BUILTIN_DOMAIN_RID,DOMAIN_ALIAS_RID_ADMINS,0, 0, 0, 0, 0, 0,&pAdminSID))
{
goto cleanup;
}
///////////////////
EXPLICIT_ACCESS ea;
ZeroMemory(&ea, sizeof(EXPLICIT_ACCESS));
if(lProtectService == 0)
ea.grfAccessPermissions = KEY_ALL_ACCESS;
else
ea.grfAccessPermissions = SERVICE_START | READ_CONTROL | DELETE;
ea.grfAccessMode = SET_ACCESS;
ea.grfInheritance= NO_INHERITANCE;
ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
ea.Trustee.TrusteeType = TRUSTEE_IS_GROUP;
ea.Trustee.ptstrName = (LPTSTR) pAdminSID;
////////////////////////////////////////////
dwError = SetEntriesInAcl(1, &ea, pacl, &pNewAcl);
if(dwError != ERROR_SUCCESS)
{
goto cleanup;
}
if(!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION))// Initialize a NEW Security Descriptor.
{
goto cleanup;
}
if(!SetSecurityDescriptorDacl(&sd, TRUE, pNewAcl, FALSE))// Set the new DACL in the Security Descriptor.
{
goto cleanup;
}
if(!SetServiceObjectSecurity(schService, DACL_SECURITY_INFORMATION, &sd))// Set the new DACL for the service object.
{
goto cleanup;
}
bSuccess = TRUE;

cleanup:
if(pNewAcl)
LocalFree((HLOCAL)pNewAcl);
if(bRelease)
{
if(psd)
{
LocalFree(psd);
}
}
if(schService)
CloseServiceHandle(schService);
if(schManager)
CloseServiceHandle(schManager);
}
catch(...)
{
return bSuccess;
}
return bSuccess;
}

Here are the steps
for using ‘psexec’ command:

1. Download PSEXEC
and unzip to some folder.

2. Open an elevated
CMD prompt as an administrator.

3. Navigate to the
folder where you unzipped PSEXEC.EXE

4. Run: PSEXEC -i -s
-d CMD

5. You will have a
new CMD prompt open, as though by magic.

6. In the new CMD prompt,
prove who you are: WHOAMI/USER

7. Run the command:
sc stop TestService

Here is the download
link: 
PsExec
— Windows Sysinternals

Our service (TestService) is a Windows Service, and the TestService.exe
is also running on SYSTEM account.

If we try the same (psexec command) for ‘RpcSs (Remote Procedure Call)’
service, then we can’t stop this service. The error message is ‘[SC] ControlService FAILED 1052: The requested control is not valid for this service’.

So how can I prevent this ‘psexec’ command from Stopping our Service/Kill
Process? Please help.

Thanks,

RVR

  • Edited by

    Tuesday, October 30, 2018 12:48 PM

I’m trying to stop the service mshidkmdf, but it won’t stop despite the fact it’s STOPPABLE. I’m able to stop the driver from device manager (the device stack is \Driver\mshidkmdf and the description is HID-compliant touch screen). When I run sc query mshidkmdf, I get:

SERVICE_NAME: mshidkmdf
        TYPE               : 1  KERNEL_DRIVER
        STATE              : 4  RUNNING
                                (STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN)
        WIN32_EXIT_CODE    : 0  (0x0)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x0

which implies that the service is STOPPABLE. But, when I run sc stop mshidkmdf, I get:

[SC] ControlService FAILED 1052: 

The requested control is not valid for this service.

and when I run net stop mshidkmdf, I get:

The requested pause, continue, or stop is not valid for this service.

More help is available by typing NET HELPMSG 2191.

I know the service is running because a) my touch screen is running and b) when I run sc start mshidkmdf, I get:

[SC] StartService FAILED 1056:

An instance of the service is already running.

My goal is to stop the device (my touch screen) that is run by the driver through the command line, but as far as I understand the driver and the service are the same thing.

  • AlLSTL

Пишу kernel-mode драйвер на С++ для Windows.
Отлаживаю его через SoftICE и DebugView.
Есть такой код:

Код

#include <ntddk.h>
#include <wdf.h>

DRIVER_INITIALIZE DriverEntry;
EVT_WDF_DRIVER_DEVICE_ADD EvtDeviceAdd;

VOID Unload(_In_ PDRIVER_OBJECT  pDriverObject) {
	KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "Unload driver"));
	DbgPrint("Unload Driver");
	IoDeleteDevice(pDriverObject->DeviceObject);
	return;
}

NTSTATUS DriverEntry(_In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath) {
	NTSTATUS status = STATUS_SUCCESS;
	
	WDF_DRIVER_CONFIG config;

	KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "Driver Entry has been started"));
	DbgPrint("Driver Entry");
	
	WDF_DRIVER_CONFIG_INIT(&config, &EvtDeviceAdd);
	
	status = WdfDriverCreate(DriverObject, RegistryPath, WDF_NO_OBJECT_ATTRIBUTES, &config, WDF_NO_HANDLE);

	DriverObject->DriverUnload = &Unload;

	return status;
}

NTSTATUS EvtDeviceAdd(_In_ WDFDRIVER Driver, PWDFDEVICE_INIT DeviceInit) {
	UNREFERENCED_PARAMETER(Driver);

	NTSTATUS status = STATUS_SUCCESS;

	WDFDEVICE hDevice;

	KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "Device has been added"));
	DbgPrint("Device Added!");

	status = WdfDeviceCreate(&DeviceInit, WDF_NO_OBJECT_ATTRIBUTES, &hDevice);

	return status;
}

Я его компилирую, подписываю, регистрирую и запускаю.
Смотрю в DebugView — вижу сообщение «Driver Entry», т.е была вызвана функция DriverEntry.
После чего драйвер просто то-ли зависает, то-ли не доходит до следующей функции, потому что сообщение «Device Added» не появляется, а при попытке sc stop MyDriver — получаю ошибку

[SC] ControlService: ошибка: 1052:

Команда неуместна для данной службы.

В чём проблема? Драйвер удаляется только после перезагрузки. Не очень-то удобно, вдруг я пишу «одноразовый драйвер», и не хочу перезагружаться, что бы его использовать, а после сразу выгрузить?


  • Вопрос задан

  • 153 просмотра

Проблема была в коде драйвера.
Вот рабочий Hello World

#include <ntddk.h>  
#include <wdm.h>

VOID DriverUnload(PDRIVER_OBJECT Driver)
{
	UNREFERENCED_PARAMETER(Driver);
	return;
}

NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObject, PUNICODE_STRING RegistryPath)
{
UNREFERENCED_PARAMETER(pDriverObject);
UNREFERENCED_PARAMETER(RegistryPath);
DbgPrint("Hello, world!");
pDriverObject->DriverUnload = 
return STATUS_SUCCESS;
}

Как оказалось, не всегда для драйвера нужно создавать устройство (IoCreateDevice), что бы потом в Unload прописать его удаление. Достаточно просто добавить функцию Unload и добавить её в pDriverObject, и всё заработает.

Пригласить эксперта


  • Показать ещё
    Загружается…

21 сент. 2023, в 12:34

2000 руб./за проект

21 сент. 2023, в 12:17

80000 руб./за проект

21 сент. 2023, в 12:08

3000 руб./за проект

Минуточку внимания

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Control ошибка game rmdwin7 f exe
  • Controller remlicht вольво ошибка
  • Control ошибка сохранения
  • Contact card issuer ошибка 1с
  • Company of heroes критическая ошибка выполнение прервано

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии