Detecting a debugger without timing it
Nebula.NET can ask the OS and the runtime, point-blank, whether a debugger is attached — Debugger.IsAttached, IsDebuggerPresent, the PEB BeingDebugged byte, and NtQueryInformationProcess with ProcessDebugPort/Flags/ObjectHandle. Here are the real P/Invoke signatures, the constants, the IL Nebula weaves in at many sites, and why a flag check raises cost rather than ending the argument.
There is a slower, surer way to catch a debugger than timing how long your code takes to run: just ask. Windows and the .NET runtime both keep a flag that says a debugger is attached to this process, and reading it costs a function call, not a calibration run. The catch is that there is no single flag. There is a managed one the CLR owns, a famous Win32 one, a byte in a kernel structure mapped into your own address space, and a family of kernel queries — and each sees a different slice of reality, each is spoofable at a different cost, and each is a one-line pattern an attacker will look for. This post is about what those signals actually are, the real P/Invoke to read them, and how Nebula.NET weaves them in so they are not all sitting in one findable method.
The managed flag sees only half the world
The obvious check is the one every .NET developer already knows:
if (System.Diagnostics.Debugger.IsAttached)
TamperState.Poison();
Debugger.IsAttached is a property backed by the CLR’s own debugger-interface state. There is a companion, Debugger.IsLogging(), which returns true when a debugger is listening for Debugger.Log output. Both are free, both are honest — and both only know about a managed debugger, one that attached through the CLR’s debugging services (ICorDebug). That is the whole problem. An attacker reverse-engineering a .NET assembly rarely attaches Visual Studio. They attach a native debugger — x64dbg, WinDbg, an unmanaged attach in a disassembler — which sits underneath the runtime and talks to the process through the OS, not through ICorDebug. The CLR never learns about it, and Debugger.IsAttached stays stubbornly false while someone single-steps your JITed code in a disassembler window.
So the managed flag is necessary but nowhere near sufficient. To see the debugger the CLR cannot, you have to drop to the OS.
The native flags the runtime cannot see
Windows records debugger state in the Process Environment Block (PEB), a per-process structure the loader maps into your own address space. The byte at a fixed offset, BeingDebugged, is set when a debugger is present. You rarely read it by hand, because the Win32 API wraps it:
using System.Runtime.InteropServices;
static class NativeDbg
{
// Reads the PEB BeingDebugged byte of the *current* process.
[DllImport("kernel32.dll", SetLastError = false)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool IsDebuggerPresent();
// Asks the kernel about any process by handle — not just our own.
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CheckRemoteDebuggerPresent(
IntPtr hProcess,
[MarshalAs(UnmanagedType.Bool)] ref bool pbDebuggerPresent);
}
IsDebuggerPresent() is a one-instruction read of that PEB byte. CheckRemoteDebuggerPresent is the more interesting of the two: it goes through the kernel and works on any process handle, so passing your own GetCurrentProcess() handle catches a debugger that cleared the user-mode PEB byte but is still attached at the kernel level.
The deepest commonly used probe is NtQueryInformationProcess in ntdll. It is undocumented-ish, but stable, and it exposes the kernel’s own view of your debug state through several information classes:
[DllImport("ntdll.dll")]
static extern int NtQueryInformationProcess(
IntPtr processHandle,
int processInformationClass,
ref IntPtr processInformation,
int processInformationLength,
out int returnLength);
// Information classes relevant to debugging:
const int ProcessDebugPort = 0x07; // non-zero IntPtr => a debug port is attached
const int ProcessDebugObjectHandle = 0x1E; // non-null handle => a kernel debug object exists
const int ProcessDebugFlags = 0x1F; // returns the INVERSE of NoDebugInherit; 0 => being debugged
Reading ProcessDebugPort (0x7) gives a non-zero pointer when a debug port is bound to the process. ProcessDebugObjectHandle (0x1E) returns a non-null handle to the kernel’s debug object — present only while a debugger is attached. ProcessDebugFlags (0x1F) is the inverted NoDebugInherit bit, so a returned value of 0 means the process is being debugged. These live in the kernel, so clearing the user-mode PEB byte — a popular first move — does not touch them. A probe reads like this:
static bool KernelSaysDebugged()
{
IntPtr port = IntPtr.Zero;
int status = NtQueryInformationProcess(
GetCurrentProcess(), ProcessDebugPort,
ref port, IntPtr.Size, out _);
return status == 0 && port != IntPtr.Zero; // NTSTATUS 0 == STATUS_SUCCESS
}
How Nebula weaves them in
The temptation — and the mistake — is to write one static bool IsDebuggerAttached() that ANDs all of these together and call it at the top of your license check. That gives an attacker a single, named, high-value method: find it once, make it return false, and every caller is defeated at a stroke. The whole point of an obfuscator’s injection pass is to avoid that choke-point.
Nebula applies these checks as a post-build IL pass, so your source never carries the P/Invoke at all. You mark the methods worth defending, and the pass scatters different probes across many sites — a managed-flag read inside one method, a PEB check folded into a second unrelated method, a kernel query buried in a third. No two sites look identical, and none of them is named AntiDebug. Reduced to source, one woven site reads like this — note there is no throw, no "debugger detected" string, and the probe is spliced into a method that does real work:
decimal ComputeQuote(Order order)
{
// ---- woven probe (one of several, each different) ----
if (Debugger.IsAttached | KernelSaysDebugged())
TamperState.Poison(); // deferred, quiet — folded into shared state
// ------------------------------------------------------
return PriceEngine.Evaluate(order);
}
At the IL level the guard is a handful of instructions in front of the real body. The load-bearing piece is the branch — and critically, Nebula does not emit it as a clean brtrue … throw. It folds the boolean into shared tamper state so the reaction is decoupled from the detection:
// if (Debugger.IsAttached | KernelSaysDebugged()) TamperState.Poison();
IL_0000: call bool [System.Runtime]System.Diagnostics.Debugger::get_IsAttached()
IL_0005: call bool MyApp.NativeDbg::KernelSaysDebugged()
IL_000a: or
IL_000b: brfalse.s IL_0012 // not debugged -> skip reaction, fall through
IL_000d: call void MyApp.TamperState::Poison()
IL_0012: ldarg.1 // original body begins here
IL_0013: call valuetype ...PriceEngine::Evaluate(...)
IL_0018: ret
Using or rather than a short-circuiting || is a small deliberate touch: both probes always execute, so an attacker watching call traces cannot infer which signal fired by seeing one call skipped. And because the reaction is TamperState.Poison() — the same decoupled, delayed state-poisoning used by Nebula’s self-integrity check — the program does not fail here. It fails later, somewhere unrelated, with no stack trace pointing back at the probe. An attacker who NOPs this one site has removed one of many, and still has a misbehaving program with no breadcrumb.
When it breaks, honestly
A flag check answers a yes/no question, and every yes/no question has a patch that forces the answer. This is not absolute protection and nobody should sell it as such.
The managed flag is trivially defeated. Debugger.IsAttached is a single property; patching its call site to load false is a minute’s work, and it only ever saw managed debuggers anyway.
The PEB byte is one byte. Clearing BeingDebugged in the PEB is the first thing every anti-anti-debug tool does, which is exactly why IsDebuggerPresent() alone is weak — and why the kernel queries matter, because they survive it.
The kernel queries can be hooked. A determined attacker hooks NtQueryInformationProcess to lie, or runs under a debugger that hides from these classes entirely. Nothing read from user mode is unspoofable.
The P/Invoke is a pattern. A DllImport("ntdll.dll") of NtQueryInformationProcess with class 0x1E is itself a signature an attacker greps for. That is why the probes must be obfuscated — the imports hidden, the constants encrypted, the call sites buried in control-flow flattening — so finding one does not reveal the shape of the rest.
The honest framing is the same as for timing: each signal raises the cost, none of them ends the argument. The value is in the layering. The managed flag is free and catches the lazy case. The PEB byte catches a little more. The kernel queries catch the native debugger the first two miss and survive the easy spoof. Scatter them across many sites, hide them behind obfuscation, and tie them into a tamper response that fails quietly and late, and an attacker has to find and neutralise all of them, not one — under time pressure, with no error message to guide the search.
Turning it on
API-based anti-debug injection is a Nebula Pro capability, applied as a post-build IL pass so your source never carries the P/Invoke. You pick which methods get probed — the license check, the key derivation, the handful of regions where watching the process run is the attack — rather than paying the call everywhere. Pair it with controlFlow and encryptStrings so the imports and constants are not sitting in the open, pair it with the timing checks that catch a stepping debugger even when the flags are clean, and let the decoupled tamper response keep the reaction far from the detection. One signal is a speed bump. Four signals, scattered and obfuscated and wired to a delayed reaction, are a layered defence.
Try Nebula.NET
Harden your .NET code in minutes — start with the free edition.