DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Edited on Originally published at delta1labs.com

How C# records leak their property names

Take a record that models something you would rather a competitor not read off your binary:

public record Order(string CustomerId, decimal Total, string PromoCode);
Enter fullscreen mode Exit fullscreen mode

Run it through full renaming, open the result in a decompiler, and the type is now called a, its properties are b, c, d, and most of your code is the unreadable wall you paid for. Then you open the generated ToString and it reads, in plain text, "CustomerId = ", ", Total = ", ", PromoCode = ". Your entire domain vocabulary is sitting there, in a Release build, with no PDB anywhere near it.

This is not the renamer failing. It is a consequence of what the C# compiler synthesizes for a record and where it stores the text — and once you see the two places names live, both the leak and the fix are obvious.

What a record compiles to

A record is not a special metadata shape. It is an ordinary class (or struct) for which the compiler generates a fixed set of members: the positional properties, a copy constructor, Clone, value Equals/GetHashCode, the ==/!= operators, Deconstruct, an EqualityContract property, and — the part that matters here — an override of ToString plus a helper called PrintMembers. Decompile the Order above and the display logic comes back as:

public override string ToString()
{
    StringBuilder builder = new StringBuilder();
    builder.Append("Order");
    builder.Append(" { ");
    if (PrintMembers(builder))
        builder.Append(' ');
    builder.Append('}');
    return builder.ToString();
}

protected virtual bool PrintMembers(StringBuilder builder)
{
    builder.Append("CustomerId = ");
    builder.Append((object)CustomerId);
    builder.Append(", Total = ");
    builder.Append(Total.ToString());
    builder.Append(", PromoCode = ");
    builder.Append((object)PromoCode);
    return true;
}
Enter fullscreen mode Exit fullscreen mode

Look closely at what those two methods do with names. The type name Order is not read from GetType().Name — it is a string literal the compiler hardcoded. Each member label — "CustomerId = ", ", Total = ", ", PromoCode = " — is likewise a literal. None of this is a reflective lookup against live metadata; it is text the compiler baked in at build time.

Two heaps, one renamer

Here is the crux. The name CustomerId exists in the assembly in two entirely different places.

As a property and field name, it is a row in the Property and Field metadata tables whose name points into the #Strings heap. That is the name the CLR exposes through reflection, the name a renamer is designed to rewrite. Rename the record and this becomes b.

As the text "CustomerId = " inside PrintMembers, it is a ldstr instruction whose operand points into the #US (user string) heap — the heap that holds every string literal your code ever wrote. In IL the body of PrintMembers is a sequence of plain loads and calls:

ldarg.1
ldstr      "CustomerId = "
callvirt   instance class [System.Runtime]System.Text.StringBuilder
             System.Text.StringBuilder::Append(string)
pop
ldarg.1
ldarg.0
call       instance string Order::get_CustomerId()
...
ldstr      ", Total = "
...
ldstr      ", PromoCode = "
Enter fullscreen mode Exit fullscreen mode

A name renamer rewrites metadata-table names — types, methods, fields, properties, parameters. It does not rewrite ldstr operands, and it is right not to: a string literal is data, and silently rewriting the contents of your strings would change your program's behaviour. So the #Strings entry CustomerId becomes b, and the #US entry "CustomerId = " stays exactly as it was. The decompiler reads PrintMembers, sees the untouched literals, and hands your whole model back.

A record name lives in two heaps. Renaming reaches the metadata name in #Strings; only string encryption reaches the literal copy in #US.

Why ToString still prints the right thing

There is a second, pleasant surprise hiding in the same fact. Because the labels are literals rather than reflective lookups, renaming the record does not change its runtime output. After the type is a and the properties are b, c, d, calling ToString() still yields:

Order { CustomerId = AC-9931, Total = 149.00, PromoCode = LAUNCH }
Enter fullscreen mode Exit fullscreen mode

The CLR never consulted the renamed #Strings names to produce that — it appended the baked-in #US literals and the live property values. So your structured logs, your ToString-based diagnostics and your support dumps keep reading in your own vocabulary even after a full rename. That is exactly why the leak is easy to miss: the output looks correct, so nothing prompts you to check whether the plaintext is still in the binary. It is.

The fix is string encryption, not renaming

Renaming was never going to close this, because the thing that leaks is a literal, not a name. The transform that reaches #US literals is string encryption. Nebula lifts the ldstr operands out of the user-string heap into an encrypted blob and rewrites each call site to go through a decryption routine, so PrintMembers compiles to something closer to:

ldarg.1
ldc.i4     0x2A        // token/offset of the encrypted entry
call       string <Nebula>::Decrypt(int32)
callvirt   instance class StringBuilder StringBuilder::Append(string)
Enter fullscreen mode Exit fullscreen mode

The static image no longer contains the bytes C u s t o m e r I d anywhere; a decompiler sees Decrypt(0x2A) and a blob. At runtime the plaintext is reconstructed in memory the instant before it is appended, so ToString() produces the identical string it always did. You keep readable logs and lose the free dictionary of your domain model.

Configuring it is a matter of making sure the generated record methods are in the string-encryption scope — they are ordinary methods on the type, so a type-level rule covers them:

<Rules>
  <!-- Encrypt string literals across the contract models, including the
       compiler-generated ToString/PrintMembers on each record. -->
  <Rule pattern="type MyApp.Domain.*" stringEncryption="true" rename="true" />
</Rules>
Enter fullscreen mode Exit fullscreen mode

If you would rather the literals never exist in the first place, the language gives you a second lever: write your own ToString. When a record declares an explicit ToString, the compiler suppresses its generated one and emits no PrintMembers for those members, so there are no labels to leak — at the cost of maintaining the method by hand and keeping it in step as the record grows.

When it still bites

String encryption closes the ToString leak, but a record can expose its member names by other routes, and those are separate problems. If you serialize a record with System.Text.Json and no [JsonPropertyName], the serializer reflects over the renamed properties and will happily emit {"b": "...", "c": 149.00} — breaking your JSON contract, a pitfall that belongs to serialization, not ToString. nameof(order.CustomerId) anywhere in your own code compiles to a #US literal just like the generated labels, so it leaks and needs the same string encryption. And EqualityContract returns typeof(Order) as a metadata token, which renames cleanly and leaks nothing — a useful reminder that not every generated member is a liability.

Takeaway

A record hands a decompiler your domain vocabulary not through its metadata names, which renaming handles, but through the string literals the compiler bakes into ToString and PrintMembers in the #US heap, which renaming deliberately leaves alone. The tell is that ToString keeps printing the original names even after a clean rename — proof the plaintext is still shipping. The right transform is string encryption, which removes the literals from the static image while leaving the runtime output untouched. Protecting a model is two moves, not one: rename the names, and encrypt the strings that quietly duplicate them. Nebula Pro does both in a single pass; the mistake is assuming renaming alone covered a type whose most readable description it generated for you.

Top comments (0)