Pages

Friday, May 22, 2015

[C/C++] Using RtlAdjustPrivilege to detect debugger.

A basic way using RtlAdjustPrivilege to detect the debugger (OllyDbg and IDA demo 6.6)
As usually but not (enabled by default) for all debugger, the Debugger must acquiring debug privilege
to work with its complete capacity.
The snippet is simple and probably already used but I write it as simple as possible to get a clear ASM code
inside the debugger.

RtlAdjustPrivilege: Enables or disables a privilege from the calling thread or process.

NTSTATUS RtlAdjustPrivilege
 (
  ULONG    Privilege,     //[In]    Privilege index to change.
  BOOLEAN  Enable,        //[In]    If TRUE, then enable the privilege otherwise disable.
  BOOLEAN  CurrentThread, //[In]    If TRUE, then enable in calling thread, otherwise process.
  PBOOLEAN Enabled        //[Out]   Whether privilege was previously enabled or disabled.
 
)


RtlAdjustPrivilege store the previous status into boolean variable
Our work is to read the contents of this variable after calling RtlAdjustPrivilege with SE_DEBUG_PRIVILEGE as parameter,
and of course if a status is already enabled then we have a likely debugging situation.


Code Snippet:
#include <windows.h>
#include <ntdll.h>

#ifdef _WIN64
#define captionMsg L"Application 64-bit"
#else
#define captionMsg L"Application 32-bit"
#endif

int WINAPI iWinMain() {
    //Boolean to check after calling RtlAdjustPrivilege.
    BOOLEAN bPreviousPrivilegeStatus; 

    RtlAdjustPrivilege(
        SE_DEBUG_PRIVILEGE,
        FALSE, // avoid to adjust privilege (DISABLE IT).
        FALSE,
        &bPreviousPrivilegeStatus);

// check if SE_DEBUG_PRIVILEGE was already acquired then voluntary crash the application,
// by calling memset with invalid pointer as parameter.        
    if (bPreviousPrivilegeStatus) 
        memset(NULL, 0, 1); //<-- BOOM! PADA BOOM!!!

    MessageBoxW(
        NULL,
        L"Nothing!",
        captionMsg,
        MB_ICONINFORMATION);

    return 0;
}

Source:
http://www.mediafire.com/download/z3udrn29pd93wvl/RtlAdjustPrivilege.rar