Please help me soon. I am writing a c++ code to run a service, it works fine on administrator account but on Non-Admin user account, OpenSCManager() function return null. Please
Probably you're calling OpenSCManager
specifying the SC_MANAGER_ALL_ACCESS
flag, which actually requires a set of privileges that are given by default only to admins. To start/stop services here you just need to specify the SC_MANAGER_CONNECT
flag, which is given by default to any authenticated user.
Now that you have a handle to the service manager, you have to use OpenService
to get a handle to the service. To have rights to start/stop the service you should specify GENERIC_READ | GENERIC_EXECUTE
as desired access (actually I think you can even narrow down the needed rights to just SERVICE_START
and SERVICE_STOP
and, if necessary, SERVICE_INTERROGATE
).
Here is the problem: standard services DACL don't grant such rights to normal users, so you should change the DACL of the service you need to start to allow normal users to start/stop it; see here. For more info about access rights for services, see here.
If, instead of a single service, you want to allow a normal user to start/stop any service, I don't know if it is possible without changing all the DACLs, but in my opinion it's definitely a bad idea.
Note that even in the single service case, if the service is running under a privileged account (e.g. LocalSystem
) or if it's a vital system service, letting unprivileged users mess with it it's still a bad idea. You should allow users to start/stop only services that aren't all that important for the system.
Out of curiosity, why do you need to let users start/stop services?