2008-07-09

In Vista, How Does the FLAGS Switch of REG.EXE Work? Part 2

Note: this content originally from http://mygreenpaste.blogspot.com. If you are reading it from some other site, please take the time to visit My Green Paste, Inc. Thank you.

Previously, I wrote about the FLAGS switch for REG.EXE in Vista and covered a technique that would set the virtualization-related flags of a registry key programmatically. This post intends to cover the other side - querying for the virtualization-related flags of a registry key. Again, we're dealing with an "undocumented" function in NTDLL.DLL - NtQueryKey:

NTSTATUS NtQueryKey(
IN HANDLE KeyHandle,
IN KEY_INFORMATION_CLASS KeyInformationClass,
OUT PVOID KeyInformation,
IN ULONG Length
OUT PULONG ResultLength );


To retrieve the flags for a key, call NtQueryKey with KeyInformationClass set to 5, which WDM.h tells us is KeyFlagsInformation.
typedef enum _KEY_INFORMATION_CLASS {
KeyBasicInformation,
KeyNodeInformation,
KeyFullInformation,
KeyNameInformation,
KeyCachedInformation,
KeyFlagsInformation,
KeyVirtualizationInformation,
MaxKeyInfoClass // MaxKeyInfoClass should always be the last enum
} KEY_INFORMATION_CLASS


REG.EXE supplies 12 for the value of the Length param, and the last 4 bytes of the buffer (KeyInformation) are modified when NtQueryKey returns. This would seem to suggest that the struct to receive the information containing the virtualization flags looks something like:
typedef struct _KEY_FLAGS_INFO {
ULONG unknown1;
ULONG unknown2;
ULONG ControlFlags;
} KEY_FLAGS_INFO, *PKEY_FLAGS_INFO;


Putting it all together, then, we have something like:
typedef NTSYSAPI NTSTATUS (NTAPI* FuncNtQueryKey)( HANDLE KeyHandle, KEY_INFORMATION_CLASS KeyInformationClass, PVOID KeyInformation, ULONG Length, PULONG ResultLength );
// ...
FuncNtQueryKey ntqk = (FuncNtQueryKey)GetProcAddress( GetModuleHandle( _T("ntdll.dll") ), "NtQueryKey" );
KEY_FLAGS_INFO kfi = {0};
HKEY hTheKey = NULL;
RegOpenKeyEx( HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Whatever"), 0, KEY_ALL_ACCESS, &hTheKey );
DWORD dwResultLen = 0;
DWORD dwNtqkResult = ntqk( hTheKey , KeyFlagsInformation, &kfi, sizeof( KEY_FLAGS_INFO ), &dwResultLen );
RegCloseKey( hTheKey );
hTheKey = NULL;


The flags (_CONTROL_FLAGS, from Part 1) are stored as a bitmask in kfi.ControlFlags.
typedef enum _CONTROL_FLAGS {
RegKeyClearFlags = 0,
RegKeyDontVirtualize = 2,
RegKeyDontSilentFail = 4,
RegKeyRecurseFlag = 8
} CONTROL_FLAGS;


The code above provides the same information as invoking REG.EXE FLAGS HKLM\Software\Whatever QUERY.

Again - note that this exploration was done on Windows Vista SP1. I would expect the content here to also apply to Windows Vista (no SP) as well as Windows Server 2008, but...

No comments: