HKEY_CURRENT_USER when under a service...


I am trying to figure out how to access the registry key:

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders

because I want to figure out where the current user's Favorites directory is located. The problem is, I am running as a service under LocalSystemAccount and HKEY_CURRENT_USER doesn't work.  Is there a way to figure out who the current logged-in user is? I tried GetUserName but it returns 'SYSTEM'.

Any ideas??

Who is Participating?
Each process on a Windows NT-based kernel (NT, 2000, XP, 2003) runs under the security context associated with the user account that started the process. This security context controls many things - obviously the permissions - but also the mapping of the user's registry hive.

Each user account on an NT system has its own registry hive. These hives are loaded and stored under the HKEY_USERS registry key (as sub-keys having as a name the corresponding user's SID). For each process, Windows NT will map the hive corresponding to the user that launched the process to HKEY_CURRENT_USER. In other words, HKCR is just a shortcut to the actual registry hive corresponding to the user running the process.

At any one time there are many processes running on the system. Depending on what user account was used to start each of these processes, there are many HKCR (so to speak). See, HKCR doesn't really exist; it's a process specific alias.

Your service is configured to run under the SYSTEM account, thus HKCR for your process corresponds to the local system account. Other processes will have/use different HKCRs. There isn't even a concept of the HKCR corresponding to the interactive user because there may be several interactive users at any one time. For example, if you right-click on a shortcut you can choose "Run As" and launch the corresponding program under a different security context than the one corresponding to the user that has logged on to the windows station. Also, under Windows XP, you can switch between users (i.e. have multiple simultaneous windows stations). The same applies to Terminal Services and Citrix.

What you have to do from your service is the following: enumerate all processes, find one that runs under the security context of the targeted user account, obtain a token to the user (by calling OpenProcessToken), get the corresponding user’s SID (calling GetTokenInformation), convert it to textual form, and then access the user's registry hive.

If you're still interested in doing it, this article will provide you with more information:

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.