Friday, April 18, 2008

Sign a .Net assembly

Friday, April 18, 2008 Posted by Unknown ,
A .Net assembly can be easily tampered with. Using the ildasm one can get and alter the sourcecode of an assembly (as explained in a previous blog). The sollution is to sign the assembly to be sure it is not tampered with.

Let's start with the Hello.cs assembly:

[sourcecode language="CSharp"]

using System;

public class Hello
static void Main(string[] args)
Console.WriteLine("Hello World!");

To sign we need a keyset (private and public).
sn -k myKeySet.sln

compile the Hello.cs with this keyfile:
csc /keyfile:myKeySet.sln /target:exe /out:Hello.exe Hello.cs

Now we have a signed assembly. When we try to alter this with the steps in previous blog we get the following error:

Unhandled Exception: System.IO.FileLoadException: Could not load file or assembly 'Hello, Version=, Culture=neutral, PublicKeyToken=707e1a34ff51325c' or one of its dependencies. Strong name validation failed. (Exception from HRESULT: 0x8013141A)
File name: 'Hello, Version=, Culture=neutral, PublicKeyToken=707e1a34ff51325c' ---> System.Security.SecurityException: Strong name validation failed. (Exception from HRESULT: 0x8013141A)
The Zone of the assembly that failed was:

When we assemble with the keyfile again we resign the new (altered) assembly. Of course this can't be done if you don't own the private key part of the original signer ;-). Also the hash of the assembly will be different so all assemblies referencing this assembly have to be recompiled. In short words: You can't alter a signed assembly.

ilasm /out:Hello2.exe /res:Hello.res /key:myKeySet.sln


sn -R hello2.exe myKeySet.sln

This results in a new (and definitly other) assembly.