RegeditSometimes it can be useful to determine what registry key belongs to a registry key handle. And exampling is when hooking RegQueryValue so you can determine the registry key that a value belongs to instead of having to track the registry key when it’s opened.

To obtain the registry key we can pass a handle to the NtQueryKey API with which has the following signature:

To get the keyname we need to pass the KeyNameInformation enum and we can set the ReturnLength parameter to 0 to obtain the required buffer size:

Then we call NtQueryKey again passing an allocated buffer (of type KEY_NAME_INFORMATION). However in a managed language like C# there is not really good way to define an “ANYSIZE” array in a struct. So let’s just pass a pointer:

And extract the NameLength and Name string like this:

However the returned names are in a different format than what you might expect. HKLM keys are returned as \REGISTRY\MACHINE\KEY and HKCU as \REGISTRY\USER\SID\KEY so we use the following logic to alter the string into “normal” format:

The complete code and a sample how to use can be found on my github repo.