Skip to content
← All posts
· Delta1 Labs ObfuscationNebula

Obfuscating an MSBuild custom task without breaking it

A custom MSBuild task is the mirror image of a source generator. The compiler finds a generator by attribute, so you can rename the whole class freely; MSBuild finds a task by the literal type-name string written into a UsingTask element, and reads its parameters off public property names, so both are a hard external contract that renaming must not touch. This post reads what the MSBuild engine actually reflects on when it runs your task, draws the exact line between the small pinned surface and the valuable logic that renames freely, and shows the Nebula config and the verification build that catches the one failure mode that is silent.

If you have ever obfuscated a Roslyn source generator you know the happy ending: the compiler finds generators by the [Generator] attribute, never by name, so you can rename the class, its namespace and every helper with nothing special to configure. A custom MSBuild task is the exact mirror image of that, and it is worth understanding why before you point an obfuscator at one, because the failure it produces is silent.

MSBuild does not find your task by an attribute. It finds it by a type-name string that someone wrote into a UsingTask element, and it sets the task’s inputs by reflecting over public property names that match attributes in the build file. Both of those are text in a .targets file — your own, or your consumer’s project — and text in a build file does not get rewritten when your renamer picks a for the class and b for the property. Rename them and the build fails to find your task, or finds it and silently drops every input. The good news, exactly as with a generator, is that the pinned surface is small and specific, and the code you actually care about hiding is not in it.

What the engine reflects on when it runs your task

Here is a minimal, real task — the shape you ship in a tooling NuGet package:

using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace Acme.Build;

public sealed class ValidateManifest : Task   // Task : ITask
{
    [Required]
    public string ManifestPath { get; set; } = "";

    public int MaxEntries { get; set; } = 1000;

    [Output]
    public string Fingerprint { get; set; } = "";

    public override bool Execute()
    {
        var report = ManifestInspector.Analyze(ManifestPath, MaxEntries); // the valuable part
        Fingerprint = report.Fingerprint;
        if (report.HasErrors)
            Log.LogError("ACMEB001: manifest failed validation: {0}", report.Summary);
        return !Log.HasLoggedErrors;
    }
}

And here is how a consumer invokes it — either through your packaged build/Acme.Build.targets, or hand-written in their own project:

<UsingTask TaskName="Acme.Build.ValidateManifest"
           AssemblyFile="$(MSBuildThisFileDirectory)..\tasks\Acme.Build.dll" />

<Target Name="CheckManifest" BeforeTargets="Build">
  <ValidateManifest ManifestPath="$(ManifestFile)" MaxEntries="500">
    <Output TaskParameter="Fingerprint" PropertyName="ManifestHash" />
  </ValidateManifest>
</Target>

When MSBuild reaches that target it does something very specific. It loads Acme.Build.dll, calls assembly.GetType("Acme.Build.ValidateManifest") using the exact string from TaskName, instantiates it with Activator.CreateInstance, and then — for every XML attribute on the <ValidateManifest> element — it looks up a public settable property of the same name and assigns the (type-converted) value. It runs Execute(). Afterwards, for each <Output> it reads a public gettable property by the name in TaskParameter. Three different places in that sequence consume names as data: the type name, the input property names, and the output property names. None of them survive a renamer that does not know they are load-bearing.

How MSBuild drives your taskload task assemblyAcme.Build.dllGetType(TaskName)"Acme.Build.Validate…"CreateInstancepublic parameterless ctorset properties by nameManifestPath, MaxEntriesExecute() → read OutputPinned (names are a contract)• task type name (UsingTask string)• public input property names• public [Output] property names• ITask / Execute interface slot• diagnostic code strings (value)Rename-safe (hide freely)• ManifestInspector + analysis• private helpers and fields• internal model types• everything Execute calls intoWhy each name is pinnedtype name: MSBuild doesGetType on the literal stringin UsingTask — rename andthe task is not found.properties: set and read byname from XML attributes —rename and inputs go unset,outputs come back empty.Execute: it is the ITask slot;interface impls keep their slotunder renaming — just don'tdrop or re-sign it.

What is pinned, and why

The task type name is a string in UsingTask

TaskName="Acme.Build.ValidateManifest" is a string literal, and MSBuild resolves it with GetType. If Nebula renames the class to Acme.Build.a, the GetType call returns null and the build fails with “The ‘ValidateManifest’ task was not found.” There is a tempting-but-wrong fix here: because you ship the .targets file alongside the DLL in your own package, you could rename both in lockstep and keep them consistent. Resist it. Consumers write <UsingTask> by hand too, blog posts quote your task name, and your own documentation hard-codes it. The task’s public type name is API. Pin it, and pin the namespace with it.

Public property names are the parameter contract

ManifestPath, MaxEntries and Fingerprint are not ordinary properties — they are the task’s parameters, and MSBuild binds them by name to XML attributes written in consumer project files you will never see. This is the same situation as System.Text.Json binding to property names or Dapper mapping columns: the public property names are a wire contract, not an implementation detail. Rename ManifestPath and the ManifestPath="..." attribute in the build silently binds to nothing; your [Required] check throws a confusing “required parameter not set” even though the author clearly set it. Keep every public settable/gettable property that appears as a task parameter. Note the asymmetry with the class body: the names are pinned, but the method bodies and every private member are not.

The ITask surface

Execute is the ITask.Execute interface implementation (you get it via the Task base class), so renaming preserves its v-table slot automatically — MSBuild calls it through the interface, not by string. The BuildEngine and HostObject properties are interface members set by the engine; they are preserved for the same reason. The only rules are the familiar ones: do not remove the interface implementation, do not change the signature, and keep the public parameterless constructor public (the engine calls Activator.CreateInstance).

One easy-to-miss item: the diagnostic code "ACMEB001" is a public contract. Teams grep for it, suppress it in CI, and route it in log parsers. String encryption is fine — the value is reconstructed before LogError emits it — but the string’s value must not be altered.

What renames freely

Everything that matters. ManifestInspector.Analyze, the model types it returns, every private helper, the parsing, the fingerprinting, the rules engine — none of it is named in any build file, so all of it renames, and it is exactly the logic worth protecting. A task is usually a thin reflection-friendly shell wrapped around a real body of work; the shell is pinned and the work is free. As with a generator, the overwhelming majority of the assembly obfuscates like any other library. You are pinning a doorway, not a house.

The subtlety: you own the .targets, consumers own the attributes

It helps to separate the two text sources. The UsingTask type-name string usually lives in your packaged build/*.targets, so in principle it is under your control. The property-name attributes (ManifestPath="...") live in the consumer’s project and in your public docs — entirely out of your control. That means even if you were willing to rename-in-lockstep the one string you own, you still cannot touch the property names, which is most of the pinned surface anyway. The honest model is: treat the whole externally-named task surface as public API, pin it in config, and let the renamer have the body.

The Nebula config

In Nebula terms this is a library profile that pins the task’s externally-named surface and lets everything else go:

{
  "rename": {
    "enabled": true,
    "autoDetect": true,
    "keep": [
      {
        "type": "Acme.Build.ValidateManifest",
        "members": "public",
        "reason": "MSBuild GetType()s this exact name from UsingTask and binds task parameters to its public property names"
      }
    ]
  },
  "strings": { "encrypt": true },
  "preserve": [
    { "interfaceImpl": "Microsoft.Build.Framework.ITask" }
  ],
  "controlFlow": { "enabled": true, "exclude": [ "*ValidateManifest.Execute*" ] }
}

Keeping the whole public surface of the task type — rather than enumerating each property — is deliberate: it is robust against someone adding a parameter later and forgetting to update the keep list, which is the classic cause of a parameter that silently stops binding after a refactor. autoDetect already protects the ITask implementation; the explicit preserve entry is belt-and-braces. Excluding Execute from control-flow flattening is a minor performance choice (the task may run on every incremental build) and costs no protection, because Execute is a thin dispatcher — the real work is in ManifestInspector, which stays fully transformed.

Run it as part of your pack pipeline:

nebula protect --config nebula.json --in bin/Release/Acme.Build.dll --out dist/Acme.Build.dll

Verify with a real build, not a load

The failure mode here is silent, so verifying by loading the DLL proves nothing. You have to run MSBuild against the obfuscated assembly and assert on behaviour:

# point a throwaway project's UsingTask at dist/Acme.Build.dll
dotnet build tests/TaskHarness/TaskHarness.csproj -t:CheckManifest -v:normal

Three things must hold: the task resolves (no “task was not found”), the inputs bind (a deliberately-bad manifest produces ACMEB001, proving ManifestPath and MaxEntries arrived), and the [Output] flows back ($(ManifestHash) is non-empty downstream). If a parameter went unbound you will see a default-valued run rather than a crash — which is exactly why the harness asserts on the produced values, not just on exit code.

The takeaway

A custom MSBuild task is the generator’s mirror image: the compiler finds a generator by attribute and lets you rename everything, while MSBuild finds a task by a literal type-name string and binds its parameters by public property name, making both a hard external contract. Pin the task type’s public surface — the type name and every property that shows up as a task parameter — keep the ITask/Execute slot and the public constructor, and leave diagnostic-code string values intact. Then let Nebula rename and transform the entire body, which is where your actual tooling logic lives. Verify by running a real target against the obfuscated DLL and asserting on the bound inputs and outputs, because the one way this breaks is quietly.

Try Nebula.NET

Harden your .NET code in minutes — start with the free edition.