# Detecting a debugger without timing it


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:

```csharp
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:

```csharp
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:

```csharp
[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:

```csharp
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
}
```

<figure class="my-8"><svg viewBox="0 0 680 330" role="img" aria-label="Three layers of debugger-presence signals: a managed CLR flag that sees only managed debuggers, a user-mode PEB byte, and kernel queries that see native debuggers the runtime cannot" xmlns="http://www.w3.org/2000/svg" style="max-width:680px;width:100%;height:auto;font-family:system-ui,sans-serif;font-size:13px"><text x="340" y="22" text-anchor="middle" fill="#64748b" font-weight="bold">What each signal can see</text><rect x="40" y="44" width="260" height="92" rx="8" fill="#6366f1" fill-opacity="0.10" stroke="#6366f1" stroke-width="2"/><text x="170" y="66" text-anchor="middle" fill="#6366f1" font-weight="bold">Managed (CLR)</text><text x="170" y="88" text-anchor="middle" fill="#6366f1">Debugger.IsAttached</text><text x="170" y="106" text-anchor="middle" fill="#6366f1">Debugger.IsLogging()</text><text x="170" y="126" text-anchor="middle" fill="#64748b">sees: managed debugger only</text><rect x="380" y="44" width="260" height="92" rx="8" fill="#0891b2" fill-opacity="0.10" stroke="#0891b2" stroke-width="2"/><text x="510" y="66" text-anchor="middle" fill="#0891b2" font-weight="bold">User-mode (PEB)</text><text x="510" y="88" text-anchor="middle" fill="#0891b2">IsDebuggerPresent()</text><text x="510" y="106" text-anchor="middle" fill="#0891b2">BeingDebugged byte</text><text x="510" y="126" text-anchor="middle" fill="#64748b">spoofable: one byte to clear</text><rect x="140" y="176" width="400" height="96" rx="8" fill="#10b981" fill-opacity="0.10" stroke="#10b981" stroke-width="2"/><text x="340" y="198" text-anchor="middle" fill="#10b981" font-weight="bold">Kernel (NtQueryInformationProcess)</text><text x="340" y="220" text-anchor="middle" fill="#10b981">ProcessDebugPort 0x7 · ProcessDebugFlags 0x1F</text><text x="340" y="238" text-anchor="middle" fill="#10b981">ProcessDebugObjectHandle 0x1E · CheckRemoteDebuggerPresent</text><text x="340" y="260" text-anchor="middle" fill="#64748b">sees: native debugger; survives a cleared PEB byte</text><line x1="170" y1="136" x2="300" y2="176" stroke="#64748b" stroke-width="1.5" stroke-dasharray="4 4"/><line x1="510" y1="136" x2="380" y2="176" stroke="#64748b" stroke-width="1.5" stroke-dasharray="4 4"/><text x="340" y="304" text-anchor="middle" fill="#64748b">Each layer costs the attacker a different, larger defeat.</text><text x="340" y="322" text-anchor="middle" fill="#64748b">None alone is proof; together they raise the floor.</text></svg><figcaption class="text-sm text-muted mt-2">The managed flag, the user-mode PEB byte, and the kernel queries each see a different slice of the truth. A native debugger is invisible to the top layer and only reliably caught at the bottom.</figcaption></figure>

## 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:

```csharp
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](https://delta1labs.com/blog/nebula-self-integrity-hash-check-tamper-response/) — 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](https://delta1labs.com/blog/nebula-anti-debug-timing-checks-stopwatch/) 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.

