Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Start/Stop a Windows Service from an ASP.NET app - Security issues

Here's my Windows/.NET security stack:

  • A Windows Service running as LocalSystem on a Windows Server 2003 box.
  • A .NET 3.5 Website running on the same box, under "default" production server IIS settings (so probably as NETWORKSERVICE user?)

On my default VS2008 DEV environment I have this one method, which gets called from the ASP.NET app, which works fine:

private static void StopStartReminderService() {

    ServiceController svcController = new ServiceController("eTimeSheetReminderService");

    if (svcController != null) {
        try {
            svcController.Stop();
            svcController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10));
            svcController.Start();
        } catch (Exception ex) {
            General.ErrorHandling.LogError(ex);
        }
    }
}

When I run this on the production server, I get the following error from the ServiceController:

Source: System.ServiceProcess -> System.ServiceProcess.ServiceController -> IntPtr GetServiceHandle(Int32) -> System.InvalidOperationException Message: Cannot open eTimeSheetReminderService service on computer '.'.

Why is this happening, and how do I fix it?

EDIT:

The answer is below, mostly in comments, but to clarify:

  1. The issue was Security related, and occurred because the NETWORKSERVICE account did not have sufficient rights to Start/Stop a service
  2. I created a Local User Account, and added it to the PowerUsers Group (this group has almost admin rights)
  3. I don't want my whole Web App to impersonate that user all the time, so I impersonate only in the method where I manipulate the service. I do this by using the following resources to help me do it in code:

MS KB article and this, just to get a better understanding

NOTE: I don't impersonate via the web.config, I do it in code. See the MS KB Article above.

like image 543
andy Avatar asked May 04 '09 01:05

andy


2 Answers

To give IIS permission to start/stop a particular service:

  • Download and install Subinacl.exe. (Be sure to get the latest version! Earlier versions distributed in some resource kits don't work!)
  • Issue a command similar to: subinacl /service {yourServiceName} /grant=IIS_WPG=F

This grants full service control rights for that particular service to the built-in IIS_WPG group. (This works for IIS6 / Win2k3.) YMMV for newer versions of IIS.)

like image 98
Martin_W Avatar answered Oct 10 '22 06:10

Martin_W


Try adding this to your Web.Config.

<identity impersonate="true"/>
like image 44
Phaedrus Avatar answered Oct 10 '22 05:10

Phaedrus