Trevor Elliott Trevor Elliott - 16 days ago 7
C# Question

How to programatically grant "Log on as a service" to a virtual account

I'm following this guide on using virtual accounts for Windows services: https://technet.microsoft.com/library/dd548356%28v=ws.10%29.aspx?f=255&MSPPError=-2147217396

Accordingly, these types of accounts are not manually created but simply used implicitly. This guide does not mention it, but it's also required to grant the "Log on as a service" right to the non-existent virtual accounts.

For example, SQL Server Express 2014 uses virtual accounts for its services and runs them as a user much like

NT Service\MSSQL$SQLEXPRESS
. Once installed, you can find the account names in the "Log on as a service" account listing.

The problem is that I am not sure how to programmatically grant this right to a virtual account. I've looked at using the
LsaAddAccountRights
function using pinvoke but it requires specifying the SID of the account. I do not believe that a virtual account has an SID.

How can I grant logon as a service rights to a virtual account, the way Microsoft does with SQL Server Express?

Answer

By default, the "log on as a service" right is granted to ALL SERVICES so as your self-answer says you don't need to add each service explicitly. However, you might need to do so if the configuration has been modified. (That's presumably why the SQL installer does so.)

Virtual service accounts do have SIDs, which have a 1:1 correspondence with the service name. There is even a command line tool that can calculate them in advance if you need to:

C:\>sc showsid xyzzy

NAME: xyzzy
SERVICE SID: S-1-5-80-1601682549-2674398373-2289982826-1892655095-2161370298

I can't find an API to do this calculation in advance, once you have installed the service (note that the logon right is only needed in order for the service to start successfully, not in order to install it) you can look up the SID in the same way you would look up any other SID, e.g., LookupAccountName().

Comments