How timing checks catch a stepping debugger
Flatten the control flow, encrypt every string, and a determined attacker still has one move left: attach a debugger and watch the code run. They set a breakpoint after your strings decrypt and read the plaintext out of
Flatten the control flow, encrypt every string, and a determined attacker still has one move left: attach a debugger and watch the code run. They set a breakpoint after your strings decrypt and read the plaintext out of memory; they step through your license check and flip the verdict. Static obfuscation does nothing against someone watching the program execute. But watching has a tell. A human stepping through code is thousands of times slower than a CPU running it, and that latency is measurable from inside the process. This post is about the specific stub Nebula injects to measure it — what it looks like in C# and IL, and the hard part nobody mentions: not firing on honest users.
The signal: a human is slow
A side-effect-free block of arithmetic costs microseconds. Set a breakpoint inside it and the block now takes as long as it takes a person to notice the debugger stopped, look at a few locals, and press F10 — seconds, not microseconds. Single-stepping is the same story spread across every instruction. The ratio between "ran normally" and "someone is stepping through this" is not 2× or 10×; it is commonly five or six orders of magnitude. That enormous gap is what makes timing viable at all, because it leaves room for a threshold that honest jitter never reaches.
The naive version everyone writes first looks like this:
static bool LooksStepped()
{
var sw = Stopwatch.StartNew();
long acc = 0;
for (int i = 0; i < 1000; i++) acc += i * 31 + (acc & 7);
sw.Stop();
return sw.Elapsed.TotalMilliseconds > 50 && acc != long.MinValue;
}
It works in a demo and fails in production — it allocates a Stopwatch, it picks an absolute 50 ms threshold out of the air, and one GC pause makes it lie. Everything interesting is in fixing those three mistakes.
What Nebula actually injects
Nebula does not ask you to write the loop. Mark a method for anti-debug protection and a post-build IL pass wraps the region: capture a timestamp on entry, run the real body, capture a timestamp on exit, and compare the delta against a calibrated budget. The counter is Stopwatch.GetTimestamp() — a static call returning the raw high-resolution tick (QueryPerformanceCounter on Windows, clock_gettime elsewhere) with no allocation, which matters because an allocation inside the measured window could trigger the very GC pause you are trying not to confuse with a debugger.
Reduced to source, the woven method reads like this:
decimal ComputeQuote(Order order)
{
long t0 = Stopwatch.GetTimestamp();
// ---- original method body runs here ----
decimal quote = PriceEngine.Evaluate(order);
// -----------------------------------------
long elapsed = Stopwatch.GetTimestamp() - t0;
if (elapsed > _budgetTicks) // orders of magnitude over calibrated normal
TamperState.Poison(); // deferred, quiet — see below
return quote;
}
_budgetTicks is not a constant in the source; it is derived at startup (next section). The comparison is a single long compare, and the reaction is folded into shared state rather than a throw, so there is no "Debugger detected" string and no stack trace pointing at the check.
At the IL level
The injected guard is small. Here is representative IL for the entry capture, the exit capture, and the branch — the original body sits between IL_0006 and the second call:
// long t0 = Stopwatch.GetTimestamp();
IL_0000: call int64 [System.Runtime]System.Diagnostics.Stopwatch::GetTimestamp()
IL_0005: stloc.0 // t0
// ---- original method body ----
IL_0006: ldarg.1
IL_0007: call valuetype ...PriceEngine::Evaluate(...)
IL_000c: stloc.2 // quote
// -------------------------------
// long elapsed = Stopwatch.GetTimestamp() - t0;
IL_000d: call int64 [System.Runtime]System.Diagnostics.Stopwatch::GetTimestamp()
IL_0012: ldloc.0
IL_0013: sub
IL_0014: stloc.1 // elapsed
// if (elapsed <= budget) goto done;
IL_0015: ldloc.1
IL_0016: ldsfld int64 ...Guard::_budgetTicks
IL_001b: ble.un IL_0023 // within budget -> skip reaction
// over budget: fold into tamper state, do not throw
IL_001d: call void ...TamperState::Poison()
IL_0023: ldloc.2 // return quote
IL_0024: ret
The load-bearing instruction is IL_001b, the ble.un. At runtime on an un-debugged process it is almost always taken, so the reaction block is skipped and the method behaves exactly as written. Note the comparison is unsigned (ble.un): the counter is monotonic so elapsed is non-negative, and unsigned compare sidesteps any wraparound edge case on the raw tick subtraction. The entire overhead on the honest path is two static calls, a subtract and a compare — nanoseconds.
The hard part: not firing on honest users
A timing check that cries wolf is worse than none — it ships a crash that only some customers, on some hardware, some of the time, can reproduce. Four things stretch a legitimate reading, and each needs an answer.
A stop-the-world GC. If a gen-2 collection suspends your thread between t0 and t1, elapsed balloons through no fault of a debugger. Answer: keep the guarded region tiny and allocation-free so a collection is unlikely to start inside it, and — critically — never treat one reading as proof.
Thread preemption. The OS scheduler can deschedule your thread mid-window. Same shape as a GC pause, same answer.
Cold JIT. The first call to a method pays for jitting. If the guarded body is jitted inside the window, the first reading is huge. Answer: calibrate after warm-up, and discard the first sample.
Slow or throttled hardware. An old CPU, a power-capped laptop, a contended VM — all run the honest workload slower. An absolute threshold like 50 ms is meaningless across that range.
The fix for all four is the same idea: measure relative, sample repeatedly, and keep the minimum. At startup, after warm-up, time the same workload several times with no debugger present and record the baseline. Because noise is one-sided — a GC pause, a preemption or a cache miss can only ever make a reading longer, never shorter — the fastest of several samples is the one closest to the true cost. Build the budget from that minimum times a wide margin:
static long Calibrate(Action work, int samples = 16)
{
work(); // warm-up: pay the JIT once, discard
long best = long.MaxValue;
for (int i = 0; i < samples; i++)
{
long t0 = Stopwatch.GetTimestamp();
work();
long dt = Stopwatch.GetTimestamp() - t0;
if (dt < best) best = dt; // keep the minimum: noise only adds time
}
// Budget sits orders of magnitude above the clean minimum, so jitter never reaches it.
return best * 1024;
}
And at the check site, do not react to a single breach. Require a run of them — a stepping human produces many slow windows in a row, while a GC pause produces exactly one:
static int _strikes;
static void Observe(long elapsed, long budget)
{
if (elapsed <= budget) { _strikes = 0; return; } // one clean reading resets
if (++_strikes >= 3) // three in a row -> act
TamperState.Poison();
}
A single GC pause trips one strike and the next clean window clears it. A debugger trips strike after strike and never clears. That N-of-M gate, combined with a budget already a thousandfold above the clean minimum, is what separates a real detector from a flaky one.
Reacting quietly
Detection is half the stub; the reaction is the other half, and it is where naive implementations give themselves away. Do not throw "Debugger detected" — that is a string to grep for and a stack trace that leads straight to the check. TamperState.Poison() in the examples does nothing visible; it flips shared state that a later, unrelated feature consults, so the symptom surfaces far from the detection in both code and time. The attacker who neutralises the obvious throw finds the program still misbehaves, with no breadcrumb back to why. Scatter several independent guards rather than one AntiDebug() method, and each one an attacker finds is a fraction of the problem, not the whole of it.
When it breaks, honestly
Timing is a probabilistic signal, not a proof, and it has real limits. An attacker who never single-steps — who sets a conditional breakpoint, lets it fire once, and reads memory without stepping — produces far less inflation, though a breakpoint hit inside the window still costs more than clean execution. Someone who stubs Stopwatch.GetTimestamp() to return a fixed delta defeats the check entirely; that is why the check must itself be obfuscated, its calls hidden by control-flow flattening so they are not a neat pattern to hook. And on genuinely pathological hardware a thousandfold-plus margin can still be too tight, which is the argument for the N-of-M gate doing the real work rather than the threshold alone.
None of this makes timing worthless. It makes it a layer. On its own it is a speed bump. Woven in alongside control-flow flattening that hides the check, string encryption that removes the breadcrumbs, and anti-tamper that notices a patched-out guard, it becomes one more thing an attacker has to find, understand and defeat — quietly, under time pressure, without a single error message to guide them.
Turning it on
Anti-debug injection is a Nebula Pro capability, applied as a post-build IL pass so your source never carries the guards. You choose which methods get wrapped — the license check, the key derivation, the handful of regions where watching the code run is the attack — rather than paying the overhead everywhere. Pair it with controlFlow and encryptStrings so the guards themselves are not sitting in the open, and keep your renaming map so you can still read production stack traces. Start narrow, protect the methods that matter, and let the calibrated budget and the N-of-M gate keep honest users out of the reaction path.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.