Search code examples
c#windows-servicesregistryuac

C# Access registry of another user


I'm having a problem with the windows service I work on currently. Basically, I store some values in HKCU registry (from a GUI tool run as administrator) and from within that GUI I am starting a service. The service uses SYSTEM account to run, and I believe that's my problem - I can't access registry keys stored with my GUI tool inside the service, as it points to a different HKCU!

How can I "redirect" the service to use the HKCU of the user it was stored with? (Actually I can pass a user name to the service or SID if someone will point me how to retrieve it in my GUI, but I don't know what should I use to "change" the user to point to the correct one)

EDIT 1:

I use a static class to access registry, it is used by both GUI and Service and the function to retrieve the base key is (rootKey is string variable holding the subkey name):

private static RegistryKey GetBaseKey(bool writable = false)
{
    try
    {
        RegistryKey reg = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64);
        RegistryKey rk = reg?.OpenSubKey("SOFTWARE", writable)?.OpenSubKey(rootKey, writable);

        return rk;
    }
    catch (Exception ex)
    {
        // handle exceptions later
    }

    return null;
}

I have found WindowsIdentity class which can provide a handle (AccessToken) for current user, should I pass it as an argument to my service and use this handle to impersonate inside the service?

EDIT 2:

I have done some stuff but it doesn't work. What I tried:

CurrentUserToken = WindowsIdentity.GetCurrent().Token; // to get current identity token

then with ServiceController.Start I added CurrentUserToken.ToString() as an argument. Within my service I initialized RegistryUserToken (IntPtr) with the passed value and I'm stuck at:

WindowsIdentity RegUser = new WindowsIdentity(RegistryUserToken)

throwing exception:

Invalid token for impersonation - it cannot be duplicated

I tried the same with AccessToken of current instance of WindowsIdentity - same exception is thrown.

Can I at all go that way? Or should I try something different?


Solution

  • Alright, I've managed to solve it going a bit different way. I've added SID variable to my Registry class and if it's not null then I open Users Registry Hive instead of HKCU. First I retrieve current's user SID (within my GUI application) using:

    WindowsIdentity.GetCurrent().User.ToString();
    

    which I pass as an argument to my service and set it for Registry class.