目的獲得手柄NtCreateKey以鍵/ NtOpenKey
我試圖讓這將創造在HKCU註冊表配置單元給定的子鍵,或打開子鍵,如果它已經存在的功能,然後返回TRUE。
NOTES
讓RegSidPath
表示與附加到user SID
一個完全合格的HKCU註冊表路徑它如\\Registry\\User\\S-1-5-20-xxxxxx-xxxxxx-xxxxxxxx-1050
讓KeyToCreate
表示特定註冊表路徑如\\Software\\MyCompany\\MySoftware\\MySubKey
CODE
我有以下功能:
BOOL CreateHKCUKey(PWCHAR RegSidPath, PWCHAR KeyToCreate) {
UNICODE_STRING uString;
RtlInitUnicodeString(&uString, RegSidPath);
OBJECT_ATTRIBUTES ObjAttributes;
InitializeObjectAttributes(&ObjAttributes, &uString, OBJ_CASE_INSENSITIVE, 0, 0);
HANDLE BaseKeyHandle = NULL;
NTSTATUS Status = NtOpenKey(&BaseKeyHandle, KEY_CREATE_SUB_KEY, &ObjAttributes);
if (NT_SUCCESS(Status) && Status != STATUS_OBJECT_NAME_NOT_FOUND) {
UNICODE_STRING KeyString = { 0 };
do {
PWCHAR NextSubKey = StrStrW((KeyString.Length == 0 ? KeyToCreate : KeyString.Buffer) + 1, L"\\");
DWORD CurrentKeyLength = lstrlenW(KeyToCreate) - lstrlenW(NextSubKey);
PWCHAR CurrentSubKey = PWCHAR(GlobalAlloc(GPTR, CurrentKeyLength + sizeof(WCHAR)));
if (CurrentSubKey != ERROR) {
memcpy(CurrentSubKey, KeyToCreate, CurrentKeyLength * sizeof(WCHAR));
CurrentSubKey[CurrentKeyLength] = UNICODE_NULL;
RtlInitUnicodeString(&KeyString, CurrentSubKey);
OBJECT_ATTRIBUTES KeyAttributes;
InitializeObjectAttributes(&KeyAttributes, &KeyString, OBJ_CASE_INSENSITIVE, &BaseKeyHandle, 0);
HANDLE CurrentHiveEntry = NULL;
Status = NtOpenKey(&CurrentHiveEntry, KEY_CREATE_SUB_KEY, &KeyAttributes);
if (RtlNtStatusToDosError(Status) == ERROR_BAD_PATHNAME) {
InitializeObjectAttributes(&KeyAttributes, &KeyString, OBJ_CASE_INSENSITIVE, &CurrentHiveEntry, 0);
DWORD DefaultDisposition;
Status = NtCreateKey(&CurrentHiveEntry, KEY_CREATE_SUB_KEY, &KeyAttributes, 0, NULL, REG_OPTION_NON_VOLATILE, &DefaultDisposition);
if (NT_SUCCESS(Status)) {
if (StrCmpNW(KeyString.Buffer + uString.Length, KeyString.Buffer, lstrlenW(KeyToCreate) == 0))
return TRUE;
else continue;
} else break;
} else break;
BaseKeyHandle = CurrentHiveEntry;
}
} while (TRUE);
}
NtClose(BaseKeyHandle);
return FALSE;
}
問題
每當代碼獲取的這部分功能
Status = NtOpenKey(&CurrentHiveEntry, KEY_CREATE_SUB_KEY, &KeyAttributes);
if (RtlNtStatusToDosError(Status) == ERROR_BAD_PATHNAME) {
的返回值始終是ERROR_BAD_PATHNAME (161)
即使當前子鍵已經存在。
問題
的原因是什麼,以及我究竟做錯了什麼?有沒有我做過的不正確的,我該如何解決?
在點失敗,'CurrentSubKey'的價值是什麼?此外,您檢查的唯一錯誤是「ERROR_BAD_PATHNAME」,如果前一個循環失敗並出現任何其他錯誤代碼,則「BaseKeyHandle」將不會指向您所期望的位置。 (哦,你正在泄漏句柄。) –
@HarryJohnston'\\ Software' - 那麼我能做些什麼來調試錯誤 –
爲什麼你需要這個NT API? – Anders