Buy Me a Coffee

Buy Me a Coffee!

Saturday, May 6, 2017

Reading Structured Binary files in C#: Part 13

First, some errata.  There was an issue with the code from the previous article, I had incorrectly been subtracting the CLR RVA address from the Section Table RVA rather than the reverse.  That meant that my starting address for the section read was off, which made the data wrong.  That is what was causing the strange Strong Name Signature entry that I was seeing earlier.

What is super interesting to me is the chance to explain how my tests didn't catch this.  The reason is that I am doing exploratory testing into the unknown.  I am writing my tests to validate my findings, not test my findings for correctness.  This is the baseline for me as I don't have a dissected .exe to compare my findings with.  You, however, do.  You have this!  For me this is validation that it is worth doing and putting out in such a public way.  Nothing I have seen presents the information in this manner.  I have updated the GitHub project with the new tests and programs.  What is cool about using the GitHub Gist for my code is that I can update the Gist and it will be reflected in the article.

On to the next section!  The .text section has the following format:

Import Address Table
CLR Header
Strong Name Signature (Optional)
IL Code and Managed Structure Exception Handling Tables (Optional)
Debug Directory (Optional)
Managed Resources (Optional)
Unmanaged Export Stubs (Optional)
VTFixup Table (Optional)
CLR Startup Stub

The assemblies are not signed, so the Strong Name Signature is not included.  I know from the code by looking in the CLR Header at the StrongNameSignature and seeing that it is 0x0 rather than the RVA of the strong name.

Next, I see if we have an IL Code and Managed Structure Exception Handling Table by checking the ExceptionTable from the OptionalHeaderDataDirectories.  In this case, all of the assemblies have 0x0 for the entry, so that optional table is not there.

The next optional entry is the Debug Directory, and we again look in the OptionalHeaderDataDirectories for an address.  About half of the assemblies contain data in the Debug entry, so I will pick one of those and dig into the value it contains.  From the .Net IL Assembler book I know that the entry contains RVA that points to a pointer to a CodeView style header that contains the path to the PDB.  I expect the header to be in the .text section, but let's add some code to see.

I looked up the format of the Debug Directory structure on MSDN and converted it to a structure:

We read it in the same way that we have been reading it, and we test it as before.  Check out the code on GitHub if you want to see the implementations.  Next I will pull the CodeView section and get the path to the PDB.  It may prove 'interesting' as the data contains a null terminated string.

Stay tuned.  Keep digging in!