DEV Community

Encrypting attributes that leak your intent

Rename everything in a .NET assembly and one thing stays in plain English.

A renamer turns your types and methods into a1, b2, c3, but open the result in a metadata viewer and the custom attributes still read like a design document: [Obsolete("replaced by the new vault API")], [Inject(typeof(IPaymentGateway))], [assembly: InternalsVisibleTo("Acme.Billing.Tests")]. The symbols are gone; the intent is not.

A reader learns you have a vault API, a payment gateway abstraction, and a billing test assembly - from metadata that renaming was supposed to have scrubbed.

The reason is structural. Renaming rewrites the #Strings heap - the names of types, methods, and fields. An attribute's arguments do not live there. They live in the #Blob heap, in a documented binary format, pointed at by a row in the CustomAttribute table, and a renamer never touches them.

So the question this post answers: how do you keep attribute arguments from leaking intent, when the one transform you reached for cannot see them? Nebula Pro's answer is a keep/strip/encrypt policy - strip the attributes nothing reads at runtime, encrypt the blobs of the ones that must remain, and rebuild them through a generated accessor.

What the blob actually stores

Take the message that gives the game away:

[Obsolete("replaced by the new vault API")]
public void SaveToLegacyVault(byte[] data) { โ€ฆ }

The [Obsolete] application compiles into a row in the CustomAttribute table - a coded token for the target method, a token for the ObsoleteAttribute(string) constructor, and an offset into #Blob. The blob at that offset is where the string lives, serialized per ECMA-335 ยงII.23.3:

.custom instance void [System.Runtime]System.ObsoleteAttribute::.ctor(string) = (
  01 00 1D 72 65 70 6C 61 63 65 64 20 62 79 20 74 // ...replaced by t
  68 65 20 6E 65 77 20 76 61 75 6C 74 20 41 50 49 // he new vault API
  00 00                                          // ..
)

Thirty-four bytes, and the whole sentence is in there in the clear. Sliced:

Bytes Meaning
01 00 Prolog - always 0x0001, little-endian
1D SerString length: compressed unsigned 29
72 65 70 โ€ฆ 41 50 49 29 UTF-8 bytes: "replaced by the new vault API"
00 00 NumNamed = 0 named arguments

The format is fixed. The 2-byte prolog 0x0001 comes first. Then the fixed arguments - the constructor's positional parameters, here a single string - serialized in signature order with no type tags and no names: a SerString is a compressed-length prefix followed by that many UTF-8 bytes (0xFF marks a null string, distinct from the 0x00 of an empty one).

After the fixed arguments comes a 2-byte NumNamed count, and then, if it is non-zero, each named argument begins with a tag byte - 0x53 for FIELD, 0x54 for PROPERTY - followed by its element type, a SerString name, and the value. (For how a decoder reconstructs the full value from these bytes, including enums and typeof arguments, see Glass's walk through the same format.)

The point for obfuscation is narrower and sharper: the string "replaced by the new vault API" is sitting verbatim in the file. Rename SaveToLegacyVault to a7 and the blob does not change one byte - the renamer rewrites #Strings, not #Blob.

The same is true of [Inject(typeof(IPaymentGateway))], whose blob carries the assembly-qualified type name; of serialization hints that name your wire contract; and of [assembly: InternalsVisibleTo("Acme.Billing.Tests")], which announces an internal seam and a test assembly to anyone who reads the manifest. None of it is code. All of it is intent, stored as data.

The caveat that scopes the whole technique

Before any attribute is touched, one rule dominates: many custom attributes are consumed by the CLR, the JIT, the loader, or a framework during type load, and they must not be stripped or encrypted.

For example:

  • StructLayout and FieldOffset decide how a type is laid out in memory.
  • MarshalAs, DllImport, and LibraryImport drive P/Invoke.
  • Serializable, security attributes, and interop attributes are read by the runtime itself, often before any of your code runs.

Remove or encrypt one of those and you do not obfuscate the program - you break it, or silently change its semantics.

And there is a second, structural limit. You cannot transparently intercept Type.GetCustomAttributes for arbitrary third-party callers. A DI container, a serializer, or a validation framework that reflects over your attributes expects the real metadata to be present; there is no hook that hands it a decrypted attribute on the fly.

So encryption is only viable for attributes in one of two categories:

  • Attributes nothing reads at runtime - these can simply be stripped. A build-time [Obsolete] message, an internal marker read only by tooling, a documentation hint: the compiler has already consumed what it needed, and the row is dead weight that only leaks intent. Delete it.
  • Attributes your own application reads through a Nebula-provided accessor - these can have their blob encrypted and be rebuilt on demand. Because your read site is under Nebula's control, it can be rewritten to decrypt and reconstruct.

Everything else is kept verbatim. This is a policy-driven, scoped transform, not a switch that encrypts every attribute in the assembly. Each CustomAttribute row is classified by policy: framework-consumed attributes are kept verbatim, attributes nothing reads at runtime are stripped, and only attributes the app reads through a Nebula accessor have their blob encrypted and rebuilt lazily at runtime.

Stripping and encrypting, concretely

For the strip case there is nothing to reconstruct. Nebula removes the CustomAttribute row and, if the blob was the only thing pointing into a #Blob or #Strings entry, that data goes too. The [Obsolete] message that only ever mattered at compile time is gone from the shipped binary: a reader sees a method with no attribute, not a method whose attribute confesses what it replaced.

For the encrypt case the row is rewritten so its blob is ciphertext (or the row is removed and the data stored as an encrypted side blob keyed by target), and every site in your code that read the attribute is redirected to a generated accessor.

Conceptually, the before:

var attr = method.GetCustomAttribute<RouteAttribute>();
var template = attr?.Template; // "/internal/vault/migrate"

becomes a call Nebula injects in its place:

// Nebula-generated accessor; blob names and key material are string-encrypted.
var template = ProtectedAttributes.GetRoute(methodToken)?.Template;

and the accessor itself decrypts the stored blob and reconstructs the value on demand:

static class ProtectedAttributes
{
  public static RouteAttribute? GetRoute(int targetToken)
  {
    if (!_blobs.TryGetValue(targetToken, out var cipher))
      return null;
    byte[] clear = Decrypt(cipher, DeriveKey()); // key derived, not stored
    return (RouteAttribute)RebuildAttribute(clear); // prolog โ†’ ctor args โ†’ named args
  }
}

RebuildAttribute runs exactly the decode the blob format demands - read the prolog, pull the fixed arguments in constructor-signature order, read NumNamed, then bind each FIELD / PROPERTY named argument - and calls the constructor and setters to produce a live instance. The route template "/internal/vault/migrate" never appears as a plaintext SerString in the file; it exists only after the accessor has decrypted and rebuilt it, in memory, at the moment your code asks.

How you drive it

In practice this is a policy, not per-attribute surgery. Nebula ships a conservative default that keeps every attribute the runtime or a known framework is likely to read, and you extend it with an allow/deny list: strip attribute types that are pure compile-time or tooling hints, mark the attribute types your own code reads through the accessor for encryption, and leave the rest alone.

The matching is by attribute type, so [Obsolete] across the whole assembly is one decision, not hundreds. See the docs for the nebula.config.json attribute-policy reference, and Nebula.NET for how this sits alongside string and resource encryption.

Where it leaks, and when it breaks

The key is reachable, so this raises cost, not a wall. Same honest caveat as string encryption: to decrypt at runtime the key must be derivable at runtime, so it is present, in some form, in the shipped assembly, and the reconstructed attribute is a live object in memory once your code reads it. An attacker who runs the program and dumps the process after the accessor fires can recover the value.

What encryption defeats is the one-click static read - decode the blob, read the message off the disk. That becomes a dynamic attack against obfuscated, string-encrypted code. Pair it with string encryption so the key material and the blob map are not themselves plaintext literals.

Encrypt a framework-consumed attribute and you break the app, not just its obfuscation. This bears repeating because it is the way this transform fails in production: the compile is green, and type load throws - or worse, marshalling silently changes. Keep the policy conservative. If a serializer, DI container, validation framework, or the runtime itself reads an attribute, keep it verbatim; only strip or encrypt attributes you have confirmed are read solely at compile time or solely through your own accessor.

Reflection over your encrypted attribute returns nothing. Because the real CustomAttribute row is gone or its blob is ciphertext, Type.GetCustomAttributes will not find the attribute for third-party code - that is the point, but it means any legitimate reflective consumer you forgot about also comes up empty. Only encrypt attributes whose read path you own and have rerouted through the accessor.

Takeaway

Renaming scrubs the #Strings heap and leaves the #Blob heap untouched, so every attribute argument - an [Obsolete] message, a DI marker, an InternalsVisibleTo target - survives verbatim and leaks the design it describes.

The fix is not to encrypt all attributes; it is a keep/strip/encrypt policy. Keep what the CLR, JIT, loader, and frameworks read. Strip what nothing reads at runtime. Encrypt the blobs of the few attributes your own code reads through a Nebula-generated accessor, and rebuild them on demand with a derived key. Scoped that way - away from anything the runtime consumes, toward the attributes that actually carry your intent - it closes a leak that renaming alone was never able to reach.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.