Showing posts with label Obfuscar. Show all posts
Showing posts with label Obfuscar. Show all posts

Wednesday, June 19, 2024

Obfuscar: how to stop build of .NET app with error when obfuscation failed

In my previous post I showed how to obfuscate ASP.Net Core web app using Obfuscar. There was however one problem: if obfuscation will fail it will be ignored by VS by default. In the current post I will show how to make such errors more visible i.e. how to cause build to fail if obfuscation failed.

First of all we need to move obfuscation logic to PowerShell file (postpublish.ps1 in this example)  located in project folder and specify it in post publish event:

  <Target Name="PostBuild" AfterTargets="Publish" Condition=" '$(Configuration)' == 'Release' ">
    <Exec Command="pwsh -ExecutionPolicy Unrestricted $(ProjectDir)postpublish.ps1 -targetFramework $(TargetFramework) -buildConfig $(Configuration) -projectDir $(ProjectDir) -publishDir $(PublishDir)" />
  </Target>

(if you are interested why pwsh command is used instead of powershell check the following article Use PowerShell in Visual Studio build events when build Docker image for .Net app)

It is up to you to implement actual obfuscation logic, in my example I will use cross platform Obfuscar dotnet global tool:

$s = dotnet tool list -g | Out-String
if (!$s.Contains("obfuscar.globaltool")) {
	Write-Host "Obfuscar global tool not installed. Installing it..."
	& dotnet tool install --global Obfuscar.GlobalTool
} else {
	Write-Host "Obfuscar global tool is already installed"
}

$targetDir = [System.IO.Path]::Combine($projectDir, $publishDir)
$obfuscarXmlPath = [System.IO.Path]::Combine($targetDir, "obfuscar.xml")
Write-Host "Obfuscating assemblies..."
[void]($output = & obfuscar.console $obfuscarXmlPath)
$output
if ($LASTEXITCODE -ne 0) {
	Write-Host "postbuild.ps1: General error Code: Obfuscation failed"
	return
}

Here we first check whether obfuscar.globaltool already installed, if not we install it. Then we run obfuscar.globaltool with specified config file (obfuscar.xml) and check exit code: if it is not 0 (0 code means success) we write the following message to the output:

 postbuild.ps1: General error Code: Obfuscation failed

That is actual trick: message has special format recognized by Visual Studio. In this case VS will understand that error happened in post publish event and will show error in the build output. More details can be found here: Emitting custom warnings/errors in Visual Studio custom build events. With this approach you will see build errors if obfuscation failed.

Monday, October 18, 2021

Obfuscar + NVelocity + anonymous types = issue

Some time ago I faced with interesting issue related with Obfuscar and anonymous types used with NVelocity template engine. If you use NVelocity for populating templates then your code may look like this:

string Merge(string templateText, params Tuple<string, object>[] args)
{
    var context = new VelocityContext();
    foreach (var t in args)
    {
        context.Put(t.Item1, t.Item2);
    }

    var velocity = new VelocityEngine();
    var props = new ExtendedProperties();
    velocity.Init(props);
    using (var sw = new StringWriter())
    {
        velocity.Evaluate(context, sw, "", templateText);
        sw.Flush();
        return sw.ToString();
    }
}

Here we pass templateText itself and tuple(s) of (key, value) pairs where key is string name of parameter used inside template (like $p) and value is object which has to be used for expanding this parameter to the real string value in resulting text (e.g. if you have "$p.Foo" inside template then pass object which has "Foo" string property set to "bar" value - then "$p.Foo" in template will be replaced by "bar").

For objects passed as parameters into this method anonymous types can be used - it is very convenient:

string text = Merge("My object $p.Foo", Tuple.Create("p", new { Foo = "bar" }));

If you will run this code as is it will return "My object foo" which is correct. But if you will try to obfuscate your code with Obfuscar then you will get unexpected result: instead of expanded template you will get original template text "My object $p.Foo" i.e. template won't be expanded to string.

The reason of this problem is that Obfuscar by default removes properties of anonymous types - there are issues about that: Anonymous class obfuscation removes all the properties or Anonymous Types. In order to solve the problem you need to instruct Obfuscar to not obfuscate anonymous types:

<Module file="MyAssembly.dll">
  <SkipType name="*AnonymousType*" skipProperties="true" skipMethods="true" skipFields="true" skipEvents="true" skipStringHiding="true" />
</Module>

After that anonymous types won't be changed and NVelocity templates will be populated to string correctly.