I am developing a .NET Windows Service using C# that runs as the SYSTEM user so that it has permissions to install software updates etc.
I want the service to download an executable file to a protected directory and launch it. However, I want to make sure that I've considered security and that it isn't possible for another user to copy a file into the directory that the service uses and then have the file executed with SYSTEM privileges.
I've looked into creating a directory that only the SYSTEM user has access to using an ACL as follows.
var localSystemIdentifier = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);
var directorySecurity = new DirectorySecurity();
directorySecurity.AddAccessRule(new FileSystemAccessRule(localSystemIdentifier, FileSystemRights.FullControl, AccessControlType.Allow));
directorySecurity.SetOwner(_localSystemIdentifier);
Directory.CreateDirectory(_pathToTempBootstrapperDirectory, directorySecurity);
Subsequent to this, I check that the owner of the directory is the SYSTEM user before I allow a cached copy of the executable file that has been downloaded to be used.
var acl = Directory.GetAccessControl(_pathToTempBootstrapperDirectory);
if (acl.GetOwner(typeof(SecurityIdentifier)) != localSystemIdentifier)
{
cache = false;
}
However, if a user with the right permissions was able to change the owner of the directory to themselves, copy in a file, and then change the owner back to the SYSTEM user, the above check would not be of any benefit.
Perhaps the only option is to always recreate the download folder with the strict ACL and redownload the file every time to prevent the possibility of the scenario above.
In short, my question is as follows; is there a way that I can create a protected directory that I can guarantee has only ever been created or modified by the SYSTEM user?