Dev.to Security πŸ” Cybersecurity πŸ‘ 2 πŸ“– 7 min read

How an assembly notices it was patched

Rename every symbol and encrypt every string, and an attacker still has a blunt, reliable move: open your assembly in an IL editor and change one byte. Flip the brtrue that guards your license check to a brfalse and the

Rename every symbol and encrypt every string, and an attacker still has a blunt, reliable move: open your assembly in an IL editor and change one byte. Flip the brtrue that guards your license check to a brfalse and the paid path runs for free. NOP out the three instructions that call your activation guard and it never runs at all. Nothing about obfuscation stops this β€” the patched program is still valid IL, still loads, still runs. What stops it is the program noticing its own bytes are not the bytes you shipped. This post is about the specific stub Nebula injects to notice: what it computes, where the expected answer lives, the genuinely awkward problem of hashing a value that contains its own hash, and the design decision that separates a real defence from a one-line throw an attacker deletes in a minute.

The move it defends against

Here is the code worth attacking β€” an ordinary gate:

if (License.Validate())
    Features.Unlock();
else
    Features.RunLimited();

Compiled, the decision is one conditional branch:

IL_0010: call      bool [App]App.License::Validate()
IL_0015: brtrue.s  IL_001e      // valid -> jump to Unlock
IL_0017: call      void [App]App.Features::RunLimited()
IL_001c: br.s      IL_0023
IL_001e: call      void [App]App.Features::Unlock()
IL_0023: ret

The attacker does not need to understand Validate(). They need one byte. The short-form brtrue.s is opcode 0x2D; brfalse.s is 0x2C. Change that single byte and the branch inverts β€” now an invalid license jumps to Unlock:

// as shipped
IL_0015: brtrue.s   IL_001e

// after a one-byte patch: 0x2D -> 0x2C
IL_0015: brfalse.s  IL_001e

Same length, same everything else, a working assembly that is now cracked. This is the most common real attack on a managed license check, and it is exactly what a self-integrity check is built to catch β€” because that one byte lives inside the method's IL, and the IL is what we hash.

The mechanism: hash yourself, compare

The idea is a checksum over the program's own bytes. At protect time, compute a hash over a region of the module and remember it. At runtime, recompute the hash over the same region and compare. If they differ, something changed the bytes between shipping and running β€” and the honest answer to "what changed my assembly after I signed off on it?" is: a patch.

Reading your own IL at runtime does not require reading the file off disk. The loaded module can resolve its own method bodies through reflection:

static byte[] HashGuardedBodies()
{
    Module module = Assembly.GetExecutingAssembly().ManifestModule;
    using var sha = SHA256.Create();
    foreach (int token in GuardedMethodTokens)      // chosen at protect time
    {
        MethodBase mb = module.ResolveMethod(token);
        byte[] il = mb.GetMethodBody().GetILAsByteArray();
        sha.TransformBlock(il, 0, il.Length, null, 0);
    }
    sha.TransformFinalBlock(Array.Empty<byte>(), 0, 0);
    return sha.Hash;
}

GetILAsByteArray() hands back exactly the bytes we care about: the method's instruction stream, the thing the attacker edits. Hashing method IL rather than the whole file is deliberate β€” the raw PE image on disk carries a strong-name signature, timestamps and layout that differ between environments, and hashing all of it invites false positives. The IL of a chosen set of methods is stable and is precisely the attack surface.

The chicken-and-egg: hashing the hash

Now the awkward part. We have to store the expected hash somewhere in the assembly, and the assembly is the thing we are hashing. That is circular. If the expected value lives in a field and that field's storage is inside the hashed region, then writing the real hash into it at protect time changes the region we just hashed β€” so the baked-in value is immediately wrong about itself. You cannot hash a field that contains the hash of yourself.

There are two clean ways out, and both amount to putting a hole in the region:

  • Exclude the storage from the region. Hash only the IL of the guarded methods, and keep the expected hash somewhere that is not in that set β€” a field initializer, a separate data blob. The bytes we hash never include the bytes we are about to write, so baking the answer in afterwards leaves the hash valid. This is the simpler design and the one that maps naturally onto "hash these method bodies."
  • Zero the field before hashing, on both sides. If the expected value genuinely must sit inside the region, take a copy of the bytes, overwrite the hash field's slot with zeros, and hash that. Do the identical zeroing at protect time and at runtime. Both sides then agree on a region with a defined hole where the hash lives, and the circularity is gone.

Nebula uses the first approach: the guarded region is the IL of the methods you selected, and the expected digest is computed over the final protected assembly and stored outside that region, after obfuscation has run. The sequence matters β€” the hash is baked in last, over the real shipping bytes, or it would be a hash of a build that never left the machine.

The expected-hash field sits outside the hashed region, so baking the digest in does not invalidate it. At runtime the same bytes are rehashed and compared; a mismatch never throws on the spot β€” it sets a flag that corrupts behaviour elsewhere.

The design that matters: delayed, decoupled reaction

The temptation is to finish the check like this:

if (!HashGuardedBodies().SequenceEqual(Expected))
    throw new InvalidOperationException("Assembly integrity check failed.");

Do not. This is the weakest possible reaction, because it tells the attacker exactly what to remove. The string "integrity check failed" is grep bait; the throw is a single branch to invert or a ret to drop in; and crucially, the reaction fires right where the check runs, so the two sit together in one method. Crack the throw and the whole defence is gone.

The durable pattern separates detection from reaction in both code and time. The check records a result quietly; something unrelated, elsewhere, consults it and goes subtly wrong:

static int _skew;   // 0 when untampered

static void Verify()
{
    if (!HashGuardedBodies().SequenceEqual(Expected))
        _skew = unchecked((int)0x9E3779B1);   // no throw, no message
}

Then, far away β€” in a pricing calculation, a cache key, a retry count β€” _skew quietly poisons a result:

// deep inside an unrelated feature, long after Verify() ran
int shards = BaseShardCount ^ _skew;   // 0 when clean; garbage when tampered
var bucket = Hash(key) % shards;       // wrong bucket, wrong answers, no error

On a clean assembly _skew is zero and everything is exact. On a patched one the program does not crash with a helpful message; it computes wrong answers in a feature that has nothing visibly to do with licensing. The attacker who found and removed the throw β€” there wasn't one β€” is left with software that misbehaves for reasons that lead nowhere near the check. Scatter several independent verifiers rather than one CheckIntegrity() method, and each one found is a fraction of the problem.

When it breaks, honestly

Self-integrity is a layer, not a wall, and it has a hard limit worth stating plainly: it is defeated if the attacker patches out the check itself. The hash-and-compare is also just IL, and if an attacker finds Verify() they can NOP it as easily as the branch it was protecting. That is precisely why the reaction is decoupled (removing the obvious throw accomplishes nothing) and why the check must be buried β€” controlFlow flattening and string encryption exist so the verifier is not a tidy, greppable pattern sitting in the open. Many small guards beat one big one.

There is a second honesty: what are "the bytes"? GetILAsByteArray() returns IL, which works for a normal JIT-compiled assembly. Under ReadyToRun or NativeAOT, methods are precompiled to native code and the IL you hash may not be what executes β€” or may not be present at all. On those targets a self-integrity check over IL protects less than it appears to, and the defence shifts to native-level protections outside this post's scope. Know your deployment model before you rely on it.

Turning it on

Self-integrity injection is a Nebula Pro capability, run as a post-build IL pass so your source never carries the stub and the expected digest is computed over the final protected assembly β€” after renaming, control-flow flattening and string encryption, over the exact bytes you ship. You choose which methods join the guarded set: the license check, the activation guard, the key derivation β€” the handful of places where a one-byte patch is the attack. Pair it with controlFlow and encryptStrings so the verifier hides in the crowd, keep your rename map so you can still read production stack traces, and lean on the decoupled reaction rather than a throw. For the licensing logic those guards protect, see Keyright; for the full protection pipeline, the Nebula docs cover where each pass fits. Start with the methods that matter, and let the program quietly notice when its own bytes are no longer yours.

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.