Manage windows service with asp.net core webapi

We’re building a webapi for our administrators. One of the features is stopping and starting a windows service on the webserver the webapi is hosted on. We needed to allow our application pool user to manage the windows service. For this we use the sc.exe tool.

First we collected the security descriptor (SID) for the application pool user with the code below.

$account = new-object System.Security.Principal.NTAccount("apppooluser");
$account.Translate([System.Security.Principal.SecurityIdentifier]).Value;
# output S-1-5-21-1003698448-2199609630-2888039566-500

Now we used se.exe to get and set the ACE for the windows service. The output of the first statement is used in the second statement, with the SID from above added before the S:

sc.exe sdshow Spooler
# output "D:(A;;CCLCSWLOCRRC;;;AU)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)"
# add the apppooluser to the list in the D: section
sc.exe sdset Spooler "D:(A;;CCLCSWLOCRRC;;;AU)(A;;RPWPCR;;;S-1-5-21-1003698448-2199609630-2888039566-500)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)"
# [SC] SetServiceObjectSecurity SUCCESS

Breakdown of the setting:

Code Explained
D: dacl_flags are used
A ACCESS_ALLOWED_ACE_TYPE
RPWPCR ADS_RIGHT_DS_READ_PROP ADS_RIGHT_DS_WRITE_PROP ADS_RIGHT_DS_CONTROL_ACCESS
S-1-5-21-1003698448-2199609630-2888039566-500 SID of the apppooluser

Now we can start and stop the windows service from our webapi. We added authentication and authorisation to the webapi to control who can perform the actions. Check-in and release this features. Done.

References

Security Descriptior Definition Language
ACE strings
Sc sdset
SC.exe

About erictummers

My work as a recruited developer changes almost every month. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Development, Security and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.