Pages

Monday, May 18, 2015

[C/C++] Protect handle from close.

Code snippet:  
#include <windows.h>
#include <stdio.h>
#include <ntdll.h>

int iWinMain() {
#ifdef _WIN64
    LPWSTR captionMsg = L"64-bit Application";
#else
    LPWSTR captionMsg = L"32-bit Application";
#endif
    WCHAR mainMsg[MAX_PATH] = {0};
    HANDLE FileHandle = NULL;
    UNICODE_STRING ObjectName;
    OBJECT_ATTRIBUTES ObjectAttributes;
    OBJECT_HANDLE_ATTRIBUTE_INFORMATION ObjectHandleAttributeInformation;

    RtlInitUnicodeString(&ObjectName, L"\\REGISTRY\\USER\\.DEFAULT");
    InitializeObjectAttributes(&ObjectAttributes, &ObjectName, OBJ_CASE_INSENSITIVE, NULL, NULL);

    LPWSTR finishedMsg = L"Failed!";

    if (NtOpenKey(
                &FileHandle,
                KEY_READ,
                &ObjectAttributes) == STATUS_SUCCESS) {

        ObjectHandleAttributeInformation.ProtectFromClose = TRUE;

        if (NtSetInformationObject(
                    FileHandle,
                    ObjectHandleInformation,
                    &ObjectHandleAttributeInformation,
                    sizeof(OBJECT_HANDLE_ATTRIBUTE_INFORMATION)) == STATUS_SUCCESS) {
//
// MessageId: STATUS_HANDLE_NOT_CLOSABLE 0xC0000235L
// MessageText: NtClose was called on a handle that was protected from close via NtSetInformationObject.
//
            LONG_PTR  ntCloseStatus = NtClose(FileHandle);
            _snwprintf(
                mainMsg,
                MAX_PATH * 2,
                L"Job done!\n\nProtected Handle: 0x%p\n"
                L"TargetName: \"%ws\"\nNtClose Status: 0x%p\n\n"
    "Try to close the protected Handle!\n\n[by stigma from I3CT]\nInsid3Code Team",
                FileHandle,
                ObjectName.Buffer,
                ntCloseStatus);

            MessageBoxW(NULL, mainMsg, captionMsg, MB_ICONINFORMATION);
            finishedMsg = L"Finished!";
        }
    }
    MessageBoxW(NULL, finishedMsg, captionMsg, MB_ICONINFORMATION);
    return 0;
}
Source:
http://www.mediafire.com/download/jiontnu194y16zq/ProtectHandleFromClose.rar