# What anti-debugging can and cannot do in .NET


If obfuscation is about stopping someone from *reading* your code, anti-debugging is about stopping them from *watching it run*. The two attacks are different. A reverse engineer defeated by a flattened, string-encrypted method does not give up — they attach a debugger, set a breakpoint after the strings are decrypted, and read the plaintext straight out of memory. They breakpoint the `if` at the end of your license check and flip the boolean. A debugger turns your running process into a transparent box. Anti-debugging makes that box harder to open.

## What the attacker is doing

The debugger attack on a protected app is usually one of two moves: *observe* or *alter*. Observe means letting the program decrypt a string, compute a key, or build a license verdict, then reading that value from a register or local at the moment it exists — no need to understand the obfuscated code that produced it. Alter means setting a breakpoint on a decision and changing the outcome: force `IsValid` to `true`, skip the throw, jump past the check. Both require a live debugger attached to your process, which is exactly the thing you can detect.

## Managed detection

The cheapest checks are built into the BCL and catch Visual Studio, most managed debuggers and the "Debug → Attach to Process" workflow:

```csharp
using System.Diagnostics;

static bool ManagedDebuggerPresent()
    => Debugger.IsAttached || Debugger.IsLogging();
```

`Debugger.IsAttached` is the obvious one. `Debugger.IsLogging()` returns true when a debugger is listening for `Debugger.Log` output, catching some cases where `IsAttached` has been faked. These are a single property each — trivial for an attacker to locate and invert — so treat them as the first tripwire, never the whole fence.

## Native detection

Managed checks miss native debuggers (WinDbg, x64dbg) and anything that attaches below the CLR. The OS knows, and exposes it:

```csharp
using System.Runtime.InteropServices;

static class Native
{
    [DllImport("kernel32.dll")]
    static extern bool IsDebuggerPresent();

    [DllImport("kernel32.dll")]
    static extern bool CheckRemoteDebuggerPresent(IntPtr hProcess, ref bool present);

    public static bool DebuggerPresent()
    {
        if (IsDebuggerPresent()) return true;
        bool present = false;
        CheckRemoteDebuggerPresent(Process.GetCurrentProcess().Handle, ref present);
        return present;
    }
}
```

`IsDebuggerPresent` reads the `BeingDebugged` byte in the process's own PEB — fast, but easy to patch. `CheckRemoteDebuggerPresent` asks the kernel about the current process, which catches debuggers that cleared the PEB flag but are still attached. Running both closes gaps that either alone leaves open.

## Timing detection

The two approaches above test a flag. A single-stepping or breakpoint-driven debugger leaves a different kind of evidence: *time*. Code that should take microseconds takes seconds when a human is stepping through it. Measure a tight, side-effect-free block and react if it ran implausibly slowly:

```csharp
static bool SteppingDetected()
{
    var sw = Stopwatch.StartNew();
    // A short deterministic workload with no I/O and no awaits.
    long acc = 0;
    for (int i = 0; i < 1000; i++) acc += i * 31 + (acc & 7);
    sw.Stop();
    // Microseconds normally; a stepping debugger inflates this by orders of magnitude.
    return sw.Elapsed.TotalMilliseconds > 50 && acc != long.MinValue;
}
```

Timing is noisy — a loaded machine or a GC pause can trip it — so use a generous threshold and never make a single timing reading fatal. Its strength is that it detects the *act of stepping*, which flag checks cannot.

<figure class="my-8"><svg viewBox="0 0 640 96" role="img" aria-label="Layered checks: managed, native and timing feed one verdict, which fails closed quietly" style="width:100%;height:auto"><defs><style>.b{fill:#eef4ff;stroke:#8eb4ff}.d{fill:#e6fffb;stroke:#2dd4bf}.t{font:600 12px system-ui;fill:#1547e0}.a{stroke:#8eb4ff;stroke-width:2;fill:none}</style><marker id="m" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto"><path d="M0 0l6 3-6 3z" fill="#8eb4ff"/></marker></defs><rect class="b" x="4" y="8" width="150" height="24" rx="6"/><text class="t" x="16" y="24">Managed (IsAttached)</text><rect class="b" x="4" y="36" width="150" height="24" rx="6"/><text class="t" x="16" y="52">Native (kernel32)</text><rect class="b" x="4" y="64" width="150" height="24" rx="6"/><text class="t" x="16" y="80">Timing (stepping)</text><path class="a" d="M156 20 C 220 20, 220 48, 276 48" marker-end="url(#m)"/><path class="a" d="M156 48 h118" marker-end="url(#m)"/><path class="a" d="M156 76 C 220 76, 220 48, 276 48" marker-end="url(#m)"/><rect class="b" x="278" y="36" width="96" height="24" rx="6"/><text class="t" x="292" y="52">One verdict</text><path class="a" d="M376 48 h30" marker-end="url(#m)"/><rect class="d" x="408" y="36" width="170" height="24" rx="6"/><text class="t" x="420" y="52" style="fill:#0d9488">Fail closed, quietly</text></svg></figure>

## Reacting without announcing yourself

How you react matters as much as how you detect. The instinct is to throw `"Debugger detected!"` — don't. That hands the attacker a string to search for and a stack trace that points straight at your check; they set a breakpoint on the throw and walk backwards to the detection, then patch it. Better responses are quiet and deferred:

- Fold the result into normal state — degrade to the unlicensed edition, return subtly wrong data, or let a later unrelated feature fail — rather than reacting at the detection site.
- Delay the reaction so the symptom is far from the check in both code and time.
- Never use a message that names debugging; never centralise all checks in one `AntiDebug` method an attacker can neuter once.

## The honest limit

Every technique here can be beaten in isolation. `IsDebuggerPresent` can be hooked to always return `false`. `Debugger.IsAttached` is one IL `callvirt` an attacker inverts with a hex editor. Timing checks can be stubbed to return a fixed small value. On its own, anti-debugging stops the casual attacker with a debugger open and little else.

Its real value is compounding. When the detection is itself control-flow-flattened and its strings encrypted, finding the check is work. When several independent checks are scattered and their reactions deferred, neutralising one does not help. When [anti-tamper](https://delta1labs.com/blog/anti-tamper-dotnet) verifies the method's integrity, patching a check out is itself detected. Anti-debugging is not the lock; it is one of the several things that have to be picked at once, and that is where protection actually comes from — [Nebula.NET](https://delta1labs.com/products/nebula) applies these as layers rather than a single switch. Used that way, the transparent box gets a lot harder to see into.

