[Anti-Analysis] Abusing CloseHandle API

[Anti-Analysis] Abusing CloseHandle API

Detecting debugger by inspecting Kernel32.CloseHandle's output.

The documentation of CloseHandle states the following:

If the application is running under a debugger, the function will throw an exception if it receives either a handle value that is not valid or a pseudo-handle value.

Because of this specific feature, this API can be abused to detect if a process is running under a debugger.

bool __is_debugged() {
    __try {
        // Passing invalid HANDLE to CloseHandle.
        // This raises an exception if the process is attached to a debugger. 
        CloseHandle((HANDLE)(ULONG_PTR)0xDEADBEEF);
    }
    __except (EXCEPTION_INVALID_HANDLE == GetExceptionCode() ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
        return true;
    }
    return false;
}

The source to the full test-case can be found in the Anti repository.

Cheers!