Object of the excersize:
I have a service that needs to connect to securly to remote sevices.
I need to be able to store the login information for the remote services in
a secure manner.
To do this I was going to create an encrypted file containing the login
information. Encrypted under the service's login account.
I want to edit this file with a setup program.
My idea was to have setup program propmt the user to "login" as the service
account and impersonate this account while writing the config file.
The basic flow of the code is this:
LogonUser(sUsername, sDomain, sPassword, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref pExistingTokenHandle);
DuplicateToken(pExistingTokenHandle, SecurityImpersonation, ref
pDuplicateTokenHandle)
WindowsIdentity newId = new WindowsIdentity(pDuplicateTokenHandle);
WindowsImpersonationContext impersonatedUser = newId.Impersonate();
FileStream stream = new FileStream("c:\\sectest\\Encrypted.txt",
FileMode.Create, FileAccess.Write, FileShare.None, 512,
FileOptions.Encrypted);
BinaryWriter bw = new BinaryWriter(stream);
bw.Write(this.textBoxText.Text);
bw.Close();
impersonatedUser .Undo();
With FileOptions.Encrypted:
If I impersonate the current windows logon (using LogonUser to get the
handle) this works. I get an encrypted file.
If I try to impersonate another user I get this exception message on the
filestream constructor. "Access to the path 'c:\\sectest\\Encrypted.txt' is
denied."
With FileOptions.None:
This works in both the above mentioned cases.
I get this error regardless of whether the file exists or not.
I have done the tests reversing two test accounts.