C# – Impersonation to get user HKEY_CURRENT_USER does not work

c

I am attempting to Impersonate an administrator account from a LocalSystem Service in order to get data from administrators HKEY CURRENT USER registry – in order to impersonate I am using the codeproject code found at the following site written by Uwe Keim: Impersonator

My source code is as follows:

using (new Impersonator("user", ".", "pass"))
{
    RegistryKey rk = Registry.CurrentUser.OpenSubKey("Software\\CompanyName");
    string sValue = rk.GetValue("Value", "").ToString();
    rk2.Close();
}

My expectation was that sValue would be from the user/pass account (as I am impersonating it) but oddly enough it is still the sValue from the LocalSystem account where my service is runnning …

Any clues on what I am doing wrong? Any help would be much appreciated.
Thanks,

Best Answer

I know this is an old thread but I recently came across the same issue (albeit from a C++ Windows service) and thought I'd share my findings, because many forums have asked the same question and none have left a satisfactory answer.

Basically, I've found two ways to approach this, though this is an answer more for C applications rather than .NET (I haven't tested with pinvoke but it may work).

Solution 1: Instead of using RegOpenKey, use RegOpenCurrentUser() to get the key handle. Apparently, the reason RegOpenKey doesn't get the impersonated user's key is because HKEY_CURRENT_USER is cached in the running thread.

Solution 2: RegDisablePredefinedCache(). This disables the cache mentioned above and lets subsequent calls to HKEY_CURRENT_USER be of the actual impersonated user. This is the solution I went with.

Hope this helps.