Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net 2.0 ServiceController.GetServices()

I've got a website that has windows authentication enable on it. From a page in the website, the users have the ability to start a service that does some stuff with the database.

It works fine for me to start the service because I'm a local admin on the server. But I just had a user test it and they can't get the service started.

My question is:


Does anyone know of a way to get a list of services on a specified computer by name using a different windows account than the one they are currently logged in with?


I really don't want to add all the users that need to start the service into a windows group and set them all to a local admin on my IIS server.....

Here's some of the code I've got:

public static ServiceControllerStatus FindService()
        {
            ServiceControllerStatus status = ServiceControllerStatus.Stopped;

            try
            {
                string machineName = ConfigurationManager.AppSettings["ServiceMachineName"];
                ServiceController[] services = ServiceController.GetServices(machineName);
                string serviceName = ConfigurationManager.AppSettings["ServiceName"].ToLower();

                foreach (ServiceController service in services)
                {
                    if (service.ServiceName.ToLower() == serviceName)
                    {
                        status = service.Status;
                        break;
                    }
                }
            }
            catch(Exception ex)
            {
                status = ServiceControllerStatus.Stopped;
                SaveError(ex, "Utilities - FindService()");
            }

            return status;
        }

My exception comes from the second line in the try block. Here's the error:

System.InvalidOperationException: Cannot open Service Control Manager on computer 'server.domain.com'. This operation might require other privileges. ---> System.ComponentModel.Win32Exception: Access is denied --- End of inner exception stack trace --- at System.ServiceProcess.ServiceController.GetDataBaseHandleWithAccess(String machineName, Int32 serviceControlManaqerAccess) at System.ServiceProcess.ServiceController.GetServicesOfType(String machineName, Int32 serviceType) at TelemarketingWebSite.Utilities.StartService()

Thanks for the help/info

like image 538
Miles Avatar asked Oct 16 '08 21:10

Miles


3 Answers

Note: This doesn't address enumerating services as a different user, but given the broader description of what you're doing, I think it's a good answer.

I think you can simplify this a lot, and possibly avoid part of the security problem, if you go directly to the service of interest. Instead of calling GetServices, try this:

string machineName = ConfigurationManager.AppSettings["ServiceMachineName"];
string serviceName = ConfigurationManager.AppSettings["ServiceName"];
ServiceController service = new ServiceController( serviceName, machineName );
return service.Status;

This connects directly to the service of interest and bypasses the enumeration/search step. Therefore, it doesn't require the caller to have the SC_MANAGER_ENUMERATE_SERVICE right on the Service Control Manager (SCM), which remote users do not have by default. It does still require SC_MANAGER_CONNECT, but according to MSDN that should be granted to remote authenticated users.

Once you have found the service of interest, you'll still need to be able to stop and start it, which your remote users probably don't have rights to do. However, it's possible to modify the security descriptor (DACL) on individual services, which would let you grant your remote users access to stop and start the service without requiring them to be local admins. This is done via the SetNamedSecurityInfo API function. The access rights you need to grant are SERVICE_START and SERVICE_STOP. Depending on exactly which groups these users belong to, you might also need to grant them GENERIC_READ. All of these rights are described in MSDN.

Here is some C++ code that would perform this setup, assuming the users of interest are in the "Remote Service Controllers" group (which you would create) and the service name is "my-service-name". Note that if you wanted to grant access to a well-known group such as Users (not necessarily a good idea) rather than a group you created, you need to change TRUSTEE_IS_GROUP to TRUSTEE_IS_WELL_KNOWN_GROUP.

The code has no error checking, which you would want to add. All three functions that can fail (Get/SetNamedSecurityInfo and SetEntriesInAcl) return 0 to indicate success.

Another Note: You can also set a service's security descriptor using the SC tool, which can be found under %WINDIR%\System32, but that doesn't involve any programming.

#include "windows.h"
#include "accctrl.h"
#include "aclapi.h"

int main()
{
    char serviceName[] = "my-service-name";
    char userGroup[] = "Remote Service Controllers";

    // retrieve the security info
    PACL pDacl = NULL;
    PSECURITY_DESCRIPTOR pDescriptor = NULL;
    GetNamedSecurityInfo( serviceName, SE_SERVICE,
        DACL_SECURITY_INFORMATION, NULL, NULL,
        &pDacl, NULL, &pDescriptor );

    // add an entry to allow the users to start and stop the service
    EXPLICIT_ACCESS access;
    ZeroMemory( &access, sizeof(access) );
    access.grfAccessMode = GRANT_ACCESS;
    access.grfAccessPermissions = SERVICE_START | SERVICE_STOP;
    access.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
    access.Trustee.TrusteeType = TRUSTEE_IS_GROUP;
    access.Trustee.ptstrName = userGroup;
    PACL pNewDacl;
    SetEntriesInAcl( 1, &access, pDacl, &pNewDacl );

    // write the changes back to the service
    SetNamedSecurityInfo( serviceName, SE_SERVICE,
        DACL_SECURITY_INFORMATION, NULL, NULL,
        pNewDacl, NULL );

    LocalFree( pNewDacl );
    LocalFree( pDescriptor );
}

This could also be done from C# using P/Invoke, but that's a bit more work.

If you still specifically want to be able to enumerate services as these users, you need to grant them the SC_MANAGER_ENUMERATE_SERVICE right on the SCM. Unfortunately, according to MSDN, the SCM's security can only be modified on Windows Server 2003 sp1 or later.

like image 147
Charlie Avatar answered Nov 10 '22 07:11

Charlie


Thanks for that line of code Charlie. Here's what I ended up doing. I got the idea from this website: http://www.codeproject.com/KB/cs/svcmgr.aspx?display=Print

I also had to add the account I'm accessing this as to the Power Users group on the server.

public static ServiceControllerStatus FindService()
        {
            ServiceControllerStatus status = ServiceControllerStatus.Stopped;
    try
            {
                string machineName = ConfigurationManager.AppSettings["ServiceMachineName"];
                string serviceName = ConfigurationManager.AppSettings["ServiceName"].ToLower();

                ImpersonationUtil.Impersonate();

                ServiceController service = new ServiceController(serviceName, machineName);
                status = service.Status;
            }
            catch(Exception ex)
            {
                status = ServiceControllerStatus.Stopped;
                SaveError(ex, "Utilities - FindService()");
            }

            return status;
        }

And here's my other class with the ImpersonationUtil.Impersonate():

public static class ImpersonationUtil
    {
        public static bool Impersonate()
        {
            string logon = ConfigurationManager.AppSettings["ImpersonationUserName"];
            string password = ConfigurationManager.AppSettings["ImpersonationPassword"];
            string domain = ConfigurationManager.AppSettings["ImpersonationDomain"];

            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;
            WindowsImpersonationContext impersonationContext = null;

            if (LogonUser(logon, domain, password, 2, 0, ref token) != 0)
                if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                    impersonationContext = new WindowsIdentity(tokenDuplicate).Impersonate();
            //

            return (impersonationContext != null);
        }

        [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
        public static extern int LogonUser(string lpszUserName, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

        [DllImport("advapi32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
        public extern static int DuplicateToken(IntPtr hToken, int impersonationLevel, ref IntPtr hNewToken);
    }
like image 39
Miles Avatar answered Nov 10 '22 06:11

Miles


You can try using ASP.NET impersonation in your web.config file and specify a user account that has the appropriate permissions:

    <system.web>
       <identity impersonate="true" userName="Username" password="Password" />
    </system.web

Take a look at this article on MSDN. I believe there are other options that do not require storing the password in the web.config file such as placing it in a registry key instead.

This will cause the ASP.NET worker process to run under the context of the specified user instead of the user logged into the web application. However, this poses a security issue and I would strongly rethink your design. You may want to consider having the ASP.NET web page in turn fire off a request to some other process that actually controls the services, even another windows service or write the request to a database table that the windows service polls periodically.

like image 1
Rich Avatar answered Nov 10 '22 07:11

Rich