0

I use DPAPI with DataProtectionScope.LocalMachine in a Windows Service. I tested my service by running it directly on my user account. It works. Also works when run as administrator.

Then I install it as a Windows Service on LocalSystem account. Then it throws something like this:

Exception Info: Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: The system cannot find the path specified.
   at System.Security.Cryptography.ProtectedData.ProtectOrUnprotect(Byte[] inputData, Byte[] optionalEntropy, DataProtectionScope scope, Boolean protect)
   at System.Security.Cryptography.ProtectedData.Unprotect(Byte[] encryptedData, Byte[] optionalEntropy, DataProtectionScope scope)

I changed service user to my user account and it works. So - the data protection fails only if the service is run as LocalSystem.

Fragment that throws:

public byte[] Unprotect(byte[] data, DataProtectionScope scope = DataProtectionScope.CurrentUser)
    => ProtectedData.Unprotect(data, null, scope.AsSystemType());

The scope is set to DataProtectionScope.LocalMachine.

I also tried to run the service as "NT Authority\NetworkService" user. Same behavior. Can't access local machine protection keys.

Why is that and how can I fix that?

Harry
  • 4,524
  • 4
  • 42
  • 81

1 Answers1

0

So, it seems like a bug in Windows DPAPI to me. It requires a user account different from LOCAL SYSTEM and NETWORK SERVICE.

As LOCAL SYSTEM is in Administrator role, I see no reason why the key access is denied for the user.

As a workaround I just use a different API.

Microsoft.AspNetCore.DataProtection - to be exact.

That API requires the new key to be created for the first time.

For practical implementation see: https://github.com/HTD/Woof/tree/master/Packages/Woof.DataProtection https://github.com/HTD/Woof/blob/master/Packages/Woof.DataProtection/Api/WindowsLocalSystemKey.cs

You can also check the https://github.com/HTD/Woof/tree/master/Demos/Woof.ServiceInstaller.TestService for testing of a data protected service configuration.

Harry
  • 4,524
  • 4
  • 42
  • 81