Experience with CheckRemoteDebuggerPresent()

Discussion in 'Mixed Languages' started by K4onashi, Jan 6, 2020.

  1. K4onashi

    K4onashi MDL Debugger

    Mar 7, 2012
    1,815
    1,988
    60
    I'm testing the waters with an application security layer. I've looked up the documentation for kernel32 CheckRemoteDebuggerPresent()

    Code:
    BOOL CheckRemoteDebuggerPresent(
      HANDLE hProcess,
      PBOOL  pbDebuggerPresent
    );
    But when registering a variable with the following, sometimes the flag will not change:

    Code:
    Dim IsAttached As Boolean = False
    CheckRemoteDebuggerPresent(Process.GetCurrentProcess().Handle, IsAttached)
    I make a check of 'IsAttached' to complete the process, and other checks to ensure the flag was set without a jump.

    I'm sure the p/invoke is correct, it works and returns true when a debugger is attached, then it doesn't set the bool for a reason unknown to me. Tested with x64dbg and IDA. Is it best to just write something myself? Or does someone with experience have input?

    Regards, K4.
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  2. K4onashi

    K4onashi MDL Debugger

    Mar 7, 2012
    1,815
    1,988
    60
    #2 K4onashi, Jan 6, 2020
    Last edited: Jan 6, 2020
    (OP)
    Do not worry, I solved it.

    Forgot I have some modules to hide stuff from the PEB, and found a way around. Maybe I should go to bed.
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  3. Michaela Joy

    Michaela Joy MDL Crazy Lady

    Jul 26, 2012
    4,082
    4,654
    150
    PBOOL is a pointer to a BOOL. Is there a syntax to tell it that the second parameter is a pointer to a BOOL?

    In C#:

    BOOL IsAttached;

    CheckRemoteDebuggerPresent(Process.GetCurrentProcess().Handle, &IsAttached);
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  4. K4onashi

    K4onashi MDL Debugger

    Mar 7, 2012
    1,815
    1,988
    60
    #4 K4onashi, Jan 7, 2020
    Last edited: Jan 26, 2020
    (OP)
    Yes, thanks. With CheckRemoteDebuggerPresent(), IsDebuggerPresent() it's now working. My issue was hiding from the PEB. Since it can easily be manipulated by switching 'BeingDebugged' flag with:

    Code:
    mov eax, dword ptr fs:[0x30]
    mov byte ptr ds:[eax+2], 0
    
    I switched to C++ and moved the checks into TLS callback:

    Code:
    VOID NTAPI TlsCallback(PVOID DllHandle, DWORD dwReason, VOID Reserved)
    {
    }
    
    Now it's allocated before the entry point, since this is the first place one would look and could easily make an unconditional jump or switch BeingDebugged to 00 in the dump. Now it's more secure I'm now looking into how to better protect, since attaching a debugger is easy.

    Regards, K4 :hug2:
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...