Click here to Skip to main content
Click here to Skip to main content

Removing Strong-Signing from Assemblies at File Level (byte patching)

By , 9 Mar 2013
 

Strong Name Remove application screenshot

Introduction

This article describes how Strong Signing works in .NET Framework 1.1 and 2.0. In particular, it is about how Strong Signing is implemented at file level - I mean, bytes in an assembly EXE or DLL. Knowing this allows me to best understand how security should and can be implemented in managed code. Lastly, we must be aware that Strong Signing assemblies is not a definitive way against hackers, as official Microsoft documentation says too.

Background

I'm going to explain how ideas in this article came to life using a particular (imaginary) scenario. John is a developer just been hired in a new company. His first task is to fix some typos in an application developed by his company. Some employee previously working there was not a native English speaker, so there were a lot of them (and that employee resigned some time ago). Anyway, he is asked to complete his assigned task by the next day. He first thinks it is a really easy job, but soon understands that the previous employee had not checked-in the latest application version to the source control. So, he only has the compiled application bits available, a hex editor, and some hours left (OK, this is a very bad situation, but this is just imaginary, so try to stay with me). He opens the executable and tries to find out the typos - he gets them and he fixes them, at least the worst ones, where the customer name is incorrect (yes, he can only overwrite existing bytes, but consider this enough for this scenario). At last, he starts the application, discovering it was a signed assembly (Sign an Assembly with a Strong Name on MSDN) and it won't load anymore. John has already read many articles on the assembly internal file format, like those by Matt Pietrek (part 1 and part 2) or Kevin Burton (here), and he knows ILDASM and Asmex, and obviously, he has a CLI Reference downloaded and waiting. With all that documentation available, he changes 6 bytes (!) in the file header, removing or disabling strong signing from the assembly, and getting a fully working application with no typos (but he has to complain about the lost source code to his boss...). 

Now, the article and the code... it's about those 6 bytes. 

Points of Interest

Questions are: what are the differences between a signed assembly and a normal one? Can a signed assembly be brought back to unsigned status simply by patching it at bytes level, without recompiling the source code? The answer to the second question is yes, it's possible. The answer to the first question would reveal how. I would not deal with the complete .NET header specifications here, there are a lot of articles explaining them (those already noted above and others like this).

For a complete Assembly Metadata reference, look at ECMA-335: CLI Partition II - Metadata (Word format) - this is referred in the next discussion. What follows are particular data structures and values related to assembly metadata. Patching (modifying) or removing (overwriting with zeroes) them restores an assembly to the unsigned status.

  1. Runtime flags in the CLI Header (documented in 25.3.3.1) - this byte means, in plain words, "Is the assembly signed?" - if yes, we have a COMIMAGE_FLAGS_STRONGNAMESIGNED value there (8). To remove the strong signing, simply reset this byte back to its current value minus COMIMAGE_FLAGS_STRONGNAMESIGNED. This usually leads to a flag value of COMIMAGE_FLAGS_ILONLY (1).
  2. StrongNameSignature RVA in CLI Header (documented in 25.3.3) - these are 8 bytes, giving an offset of public key hash data. Key is normally 160 (0xA0) bytes itself. To remove strong signing, simply overwrite those 8 bytes in the header with 00. This suggests to the assembly loader that there's no signature in the file, even if the original key is still there.
  3. Flags in Assembly Table (documented in 22.2) - this is a 4-byte bitmask of type AssemblyFlags (documented in 23.1.2). A value of PublicKey (0x0001) here means the assembly is strong signed. To remove strong signing, reset the first byte back to its current value minus PublicKey. This usually resets the flag to the SideBySideCompatible value (0x0000).
  4. PublicKey index in Assembly Table (documented in 22.2) - this is an index into the BLOB heap where the Public Key is stored. To remove strong signing, overwrite those two bytes with 00 (meaning, no Public Key available).

This process usually leads to a 6 to 12 bytes patching (depending on the bytes used for RVA), and is just enough to fool the .NET loader (version 1.1, 2.0, 3.0, 3.5, 4.0 and 4.5) into believing that the assembly is not strong signed at all. All you need is some reference and a hex editor. This approach removes strong signing from an EXE assembly and DLLs too. A bit more work (and experimenting) is needed if we are patching an assembly referenced by another one (eventually strong signed itself).

This situation requires removing the strong signing from the DLL (using the described method) and from the main executable (the one which references the DLL) and then modifying the main executable references table to report the DLL as not signed. The assembly reference table is named AssemblyRef (documented in 22.5), and contains PublicKeyOrToken, an index into the BLOB heap, indicating the public key or token that identifies the author of the referenced assembly. Overwriting the index (2 bytes) with 00 defines the assembly reference to the unsigned file.

Using the Code

Having to manually deal with .NET assembly metadata and data tables is very boring. The hard part there is to know the base table offset in the PE file, extract the index from the table, and jump to the correct address (this is usually referred to as RVA to Real Offsets). Experimenting at this using a hex editor was a very interesting job; anyway, we want a better way. At last, I found Asmex, a fantastic tool written in C# and available for free with full source code on CodeProject. Having to work with all those .NET headers and tables becomes really easy now.

Asmex source files are included unchanged, except for those exposing the two internal fields in the class Table (file TableStream.cs) using properties. We need that data so we can calculate the exact offsets in the file bytes for patching. Retrieving the file offset of particular structures and bytes is, in most cases, a simple property reading task using Asmex.

Getting file offsets and values from an assembly is done by the GetAssemblyData method. This is a relevant part (in source code, it's a bit more complex with error checking and comments):

MModule mod = new MModule(r);

cliHeaderFlag = mod.ModHeaders.COR20Header.Flags;
cliHeaderFlagOffset = mod.ModHeaders.COR20Header.Start + 16;
strongNameSignatureOffset =
 mod.ModHeaders.COR20Header.StrongNameSignature.Start;
compiledRuntimeVersion =
 mod.ModHeaders.MetaDataHeaders.StorageSigAndHeader.VersionString;
Table tableAssembly = mod.MDTables.GetTable(Types.Assembly);
publicKeyOffset =
 mod.BlobHeap.Start + tableAssembly[0][6].RawData + 1;
assemblyFlag = (uint)tableAssembly[0][5].Data;

// next loop sum tables byte length till
// reaching Assembly Table - this would
// give Assembly Table start offset
long assemblyTableOffset =
     mod.ModHeaders.MetaDataTableHeader.End;
for (int tablesCounter = 0; tablesCounter <
     Int32.Parse(Enum.Format(typeof(Types),
     Types.Assembly, "d")); tablesCounter++)
{
    assemblyTableOffset +=
         mod.MDTables.Tables[tablesCounter].RawData.Length;
}
publicKeyIndexOffset = assemblyTableOffset + 16;
assemblyFlagOffset = assemblyTableOffset + 12;

// next loop sum tables byte length till reaching
// Assembly References Table - this would give
// Assembly References Table start offset
long referenceTableOffset =
     mod.ModHeaders.MetaDataTableHeader.End;
for (int tablesCounter = 0; tablesCounter <
     Int32.Parse(Enum.Format(typeof(Types),
     Types.AssemblyRef, "d")); tablesCounter++)
{
    referenceTableOffset +=
         mod.MDTables.Tables[tablesCounter].RawData.Length;
}

At this point, we have all the data (to produce a basic user interface, take a look at the methods CLIHeaderFlagToString and AssemblyFlagToString decoding flag values to human readable format according to metadata specifications) and file offsets, so we can proceed with byte patching.

In the code, you'll find the PatchReference method to remove the Public Key evidences from the assembly references, and the PatchAssemblyStrongSigning method to modify the CLI Header and the Assembly Table.

All the stated methods are contained in the class Utility. You'll also find a helper class named AssemblyReference used to store assembly references data while reading and decoding it.

History

  • Version 2.3 is a refactored revision able to deal with PE and PE+ file formats (32 bit and 64 bit files). Thanks to sendersu for his help and hints on this!
  • Version 2.2 is a cleaned up and updated version. Project was upgraded to Visual Studio 2010, and I removed every reference to Memory-Mapped Files (to prevent crash on x64 systems), Vista Security, and changed a little icon (to reduce file size).
  • Version 2.1 is a bug fix for BLOB index sizing. Index was used as a fixed value, but this is not true. Bugs would happen on large files. Also changed application graphics to be more Vista-style, and added some code to be UAC aware.
  • Version 2.0 is the first public version. I experimented for a long time a 1.3 version, which was based on .NET Framework 1.1, but wasn't able to patch references table.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Andrea Bertolotto
Software Developer (Senior)
Italy Italy
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
AnswerRe: Your utility has a SMALL problemmemberAndrea Bertolotto1-Dec-09 20:13 
That is an intended problem and not so easy to solve. It's easy to know what assemplies are referenced by a DLL, but it's not immediate to know who is using current DLL (it could require scanning all DLL/EXE in a folder of perhaps complete disk). This could surely be done, but it's far away from my proof of concept tool.
 
Causing an automatic reboot is a feature for a program, not a bug.

GeneralTwo small bugsmemberDanielRose198130-Oct-09 1:38 
Hi!
 
I found two small bugs, which I fixed locally:
 
1) If the selected file's path contains spaces, upon restarting elevated, the path is considered as several arguments.
 
Fix: In VistaSecurity.cs, method RestartElevated(string arguments):
 
startInfo.Arguments = string.Format("\"{0}\"", arguments);
 
2) In non-English Windows installations, the name of the administrator role can be different.
 
Fix: In VistaSecurity.cs, method IsAdmin():
 
return p.IsInRole(WindowsBuiltInRole.Administrator);

GeneralRe: Two small bugsmemberAndrea Bertolotto1-Dec-09 20:16 
Thank you for spotting those out!
 
Causing an automatic reboot is a feature for a program, not a bug.

GeneralVery Nice!memberjay_dubal14-Jul-09 1:02 
Thumbs Up | :thumbsup: Thumbs Up | :thumbsup: Thumbs Up | :thumbsup: Thumbs Up | :thumbsup: Thumbs Up | :thumbsup:
GeneralProblemmemberI_gO_tO_schoOl_by_scoOter5-Jul-08 22:47 
The article is great, but the application didn't work with me.
Any way, I've managed to patch the exe file manually. And I have this error on running the exe
 
"Could not load file or assembly 'Name, Version=1.0.869.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)"
 
Also, I've altered its PublicKeyOrToken in the assembly ref of the exe to be null, as I edited this dll.
 
Got any clue what I've done wrong or what's missing ?!!
 
Familiarity sometimes keeps us from seeing the obvious.

GeneralRe: ProblemmemberAndrea Bertolotto6-Jul-08 5:13 
This is normal exception from CLR when something is not correctly patched. Maybe it's another DLL reference or some DLL loading by reflection. You could send me an example by e-mail of what you are doing and I'll try to understand why my application is not working for you.
 
Causing an automatic reboot is a feature for a program, not a bug.

QuestionInternalsVisibleTo causing issuesmemberfnfrich27-Jun-08 10:15 
When I try to remove strong signing from assemblies that make use of the InternalsVisibleTo attribute in their AssemblyInfo I end up getting FieldAccessExceptions. I'm guessing that since InternalsVisibleTo can't find the strong named dll it doesn't grant access to any internal fields. Is there any way around this?
 
By the way, thanks for the fantastic article.
AnswerRe: InternalsVisibleTo causing issuesmemberAndrea Bertolotto27-Jun-08 20:44 
As far as I know there could be a way to deal with this situation too. It requires patching and registering assembly for verification skipping. Maybe you can mail me your code and DLL and we can have a look at them.
 
Causing an automatic reboot is a feature for a program, not a bug.

QuestionHow Remove the CLI header ?memberLucianoNet4-Jun-08 16:56 
Hi,
 
How Remove the CLI header ?
To protect my source code
I need your help.
 
Thanks,
Luciano - From Brazil
AnswerRe: How Remove the CLI header ?memberAndrea Bertolotto4-Jun-08 22:48 
Removing a CLI header from a .NET executable means that is not a .NET program anymore. This could be achieved building a Win32 wrapper outside your executable (a stub), which loads file from disk, decrypt in memory and starts .NET application at last. This scheme is used by some commercial applications protectors and encrypters, but I personally don't like mixing Win32 techniques with .NET (and this kind of protection was already defeated too). A good .NET protection should not rely on Win32.
 
Causing an automatic reboot is a feature for a program, not a bug.

Generalwell writtenmemberlallous23-Oct-07 4:46 
Thanks a lot for this well written informative article!
GeneralSoftware not working under XPmember8844314-Aug-07 9:56 
Because of the vistasecurity.isadmin check it won't work on my dutch XP SP2. I changed the following lines in the source:
 
if (VistaSecurity.IsAdmin())
 
to
 
if (VistaSecurity.IsAdmin() | VistaSecurity.IsVistaOrHigher())
 
so it will work on my version of windows.
 
Thanks for this nice software
AnswerRe: Software not working under XP [modified]memberAndrea Bertolotto14-Aug-07 23:24 
I had a look at it. It seems a problem when using it in Windows XP SP2 and not being an admin. Anyway, proposed solution is not working for me. IsVistaOrHigher method in VistaSecurity class, incorrectly reports a Vista system even on Windows XP. So I also changed that method to return Environment.OSVersion.Version.Major >= 6;
 
Thanks for spotting this out!
GeneralRe: Software not working under XPmemberCoolVini17-Oct-07 22:51 
Now is working for me - thank you for this FANTASTIC program !!!!
GeneralRe: Software not working under XP [modified]memberalecan25-Oct-08 4:15 
Hi!
Please, check it. Now VistaSecurity contains:
internal static bool IsVistaOrHigher() {
  return Environment.OSVersion.Version.Major < 6;
}
 
Also code p.IsInRole(@"BUILTIN\Administrators") not valid for localized versions of Windows.
 
Thanks!
 
modified on Saturday, October 25, 2008 10:25 AM

GeneralAdd a strong namememberAlois Kraus23-Jan-07 12:37 
Hi,
 
I have created an opposite tool that adds a strong name to unsigned assemblies:
 
http://geekswithblogs.net/akraus1/archive/2007/01/23/104288.aspx
 
Perhaps someone finds it useful.
 
Yours,
Alois Kraus
 

GeneralRe: Add a strong namememberNordin Rahman29-Jan-07 4:23 
Thanks.
 
Finally... We have the very needed complimentary software for this.
 
Remove VS Add Strong Name.
 
I like you, and I love programming more. in C# & Java
GeneralRe: Add a strong namememberVertyg013-Feb-07 21:57 
Nice tool but I havent managed to test it successfully
 

C:\Program Files\Test>signer -k test.snk -outdir .\build -a test.dll -debug
Strong naming .\test.dll ...
An error occured while processing file .\test.dll: The assem
bly name was null or empty for type ##, parsed line: + "ib, Version=1.0.5000.0,
Culture=neutral, PublicKeyToken=b77a"

GeneralRe: Add a strong namememberAlois Kraus14-Feb-07 8:06 
Hi Verty,
 
I will have a look into this issue. It looks like the IL parser needs to become more robust when dealing with very long type names which are split into several lines.
 
Yours,
Alois Kraus

GeneralRe: Add a strong namememberAlois Kraus15-Feb-07 11:44 
Hi,
 
this error should go away if you download the latest source release and patch with it the version 1.0 to get rid of this error. I am currently working on a solution to represent the contents of an IL file as an object model for the most important parts. This new parser which will fix this error once and for all along with many more benefits.
 
Yours,
Alois

GeneralRe: Add a strong namememberVertyg015-Feb-07 20:12 
Thanks Smile | :)
GeneralRe: Add a strong namememberSuper Lloyd23-Jul-07 13:29 
hey cool!
I might finally able to use string name now!
(I have unsigned 3rd parties...)
GeneralRe: Add a strong namememberKent Boogaart23-Jul-07 13:45 
You could just use ILMerge (http://research.microsoft.com/~mbarnett/ILMerge.aspx) to do this:
 
ilmerge Original.dll /keyfile:KeyFile.snk /out:Signed.dll
 
Big Grin | :-D
QuestionMy case is exact the oppositememberStefan Prodan7-Sep-06 6:38 
I am working at an application that is using Evidence and others SN related stuff. So I have a assembly made by another developer and no source code... I have to include this assembly in my project but it's not signed. Can I sign this assembly with my own SN ?
Please let me know if this is possible. Thanks you.
 
http://stefanprodan.wordpress.com

AnswerRe: My case is exact the oppositememberAndrea Bertolotto8-Sep-06 1:44 
Adding strong signing to a non-signed one, working at byte level it's very hard. Zeroing key when it's there it's a matter of seconds, but adding a missing key requires inserting bytes in headers and relocating all table references (offsets). This is nearly impossible, surely it's like recompiling assembly (we can think of this like a metadata injection). The other way is trying to contact developer asking for a signed assembly or source code (possibly you can try to decompile it and recompile using a newly generated key - but this probably would break some license agreement).
 

GeneralRe: My case is exact the oppositememberNordin Rahman9-Oct-06 23:19 
If inserting new public key inside an assembly (so that it can be resigned by using sn tool) is difficult at byte level, how about doing it at text level (ie. by using ildasm/ilasm tool)? I never did on what this idea, but, have you try adding the publickey token of our own public-key in the IL text file generate by ildasm tool. For the sake of testing, I personally have success experience in changing existing assembly's publickey token via ildasm/ilasm tool.
 
I like you, and I love programming more.

GeneralRe: My case is exact the oppositememberAndrea Bertolotto19-Oct-06 20:40 
This can be done with some knowledge of IL language and metadata structures. A good book can help here like "CIL Programming: Under the Hood of .NET", "Expert .NET 2.0 IL Assembler" or "Inside Microsoft .NET IL Assembler". Or you can do it with some experimenting in ILDasm, looking at signed assemblies vs not signed ones. Anyway, working at IL level can be a problem (also legal) if assembly is obfuscated and cannot be decompiled/recompiled. This is same way obfuscators use to change assembly code without working at byte level.
AnswerRe: My case is exact the oppositememberAlois Kraus15-Jan-07 13:07 
I have succeeded in signing assemblies via an ILDAM/ILASM round trip. It was not easy but I hope to post an article in a few days at Code Project.
 
Yours,
Alois Kraus

AnswerRe: My case is exact the oppositemember- Pascal -20-Jul-07 2:24 
I kept this in my favorites, but never tried. Hope it helps
http://andrewconnell.com/blog/archive/2004/12/15/772.aspx


GeneralYou are the greatest!memberCoyotelapa29-Aug-06 1:41 
Great, just what I needed!
Thanks Big Grin | :-D
GeneralGREAT!memberJeremy_L28-Aug-06 10:01 
You are my hero!Big Grin | :-D
 
Jeremy

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130617.1 | Last Updated 10 Mar 2013
Article Copyright 2006 by Andrea Bertolotto
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid