Skip to content

Instantly share code, notes, and snippets.

@ek0
Created February 21, 2022 21:29
Show Gist options
  • Save ek0/00b578fee2370a0fac04a2a9d03e9d32 to your computer and use it in GitHub Desktop.
Save ek0/00b578fee2370a0fac04a2a9d03e9d32 to your computer and use it in GitHub Desktop.
Get object name for handle
// Returns an OBJECT_NAME_INFORMATION object pointed by name
// Caller must free `name` after usage
UNICODE_STRING* GetObjectNameInformation(HANDLE object_handle)
{
ULONG length = 0;
UNICODE_STRING* obj = (UNICODE_STRING*)malloc(sizeof(UNICODE_STRING));
NTSTATUS(*myNtQueryObject)(HANDLE, ObjectInfoClass, UNICODE_STRING*, uint32_t, PULONG) = (NTSTATUS(*)(HANDLE, ObjectInfoClass, UNICODE_STRING*, uint32_t, PULONG))GetProcAddress(GetModuleHandle("ntdll"), "NtQueryObject");
NTSTATUS status = myNtQueryObject(object_handle, ObjectNameInformation, obj, sizeof(UNICODE_STRING), &length);
if (!NT_SUCCESS(status) && (status == 0xc0000004 || status == 0x80000005))
{
// Buffer too small, reallocating.
obj = (UNICODE_STRING*)realloc(obj, length);
}
else if (!NT_SUCCESS(status) && !(status == 0xc0000004 || status == 0x80000005))
{
free(obj);
return nullptr;
}
status = myNtQueryObject(object_handle, ObjectNameInformation, obj, length, nullptr);
if (NT_SUCCESS(status))
{
return obj;
}
free(obj);
return nullptr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment