Registry

Loading Registry Hives

I needed to get a registry value out of all the Citrix profiles to resolve an migrate an application to the new farm. Simple enough I thought, enumerate the directories, Load the hive in ntuser.dat and read the value. Even found the function, win32api.RegLoadKey, on the first attempt.

However when I tried this on a local profile I got a permission issue, even as the local admin. The scant documentation mentioned I needed SE_PRIVILEGE_ENABLED but what is it and how do I get it. I could open the hive with regedit so why not with python.

Help came in the form of a post from future_retro on grokbase.com; basically you need to get a token for the your process and adjust the privilege on that.

flags = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY
htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(),flags)
loadid = win32security.LookupPrivilegeValue(None,'SeRestorePrivilege')
newprivlist = [(loadid, win32security.SE_PRIVILEGE_ENABLED)]
win32security.AdjustTokenPrivileges(htoken,0,newprivlist)

Now with the hive loaded the second part was getting the value. It is not quite as simple as passing the location but a two step process of opening the key with win32api.RegOpenKeyEx and reading the value win32api.RegQueryValueEx. Just don’t forget to close it when you are done.

To demonstrate this I have created this little program which enumerates all the directories in a given path and opens the hive if it exists. It then lists all of the keys under Software to give you some idea of the software the user has accessed in Citrix.

In the demonstration code there is a single function which takes up half of the code whose purpose is not clear from inspection. It take the key name and returns the values and subkeys as two lists in a tuple. Hope the example helps.