Search code examples
c#portable-executable

Accessing fields from an object in the PeNet API


I need to access these fields in the PeNet API. However the value returned is a uint16 and I don't actually know what to do with this. Does anyone know how I would go about accessing these fields?

I have had a go at accessing these fields however the structure provided has no ways that are obvious (to me) for accessing them. I have also tried printing out the uint16 bit by bit but this didn't provide anything particularly obvious either (there are 8 fields to be accessed so I thought it might be either the first 8 or last 8 but this was unsuccessful).

Any help would be very much appreciated as I have no idea where to look next :(

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var peHeader1 = new PeNet.PeFile(@"C:\Windows\System32\kernel32.dll");
            Console.WriteLine(peHeader1.ImageNtHeaders.OptionalHeader.DllCharacteristics.GetType());
            Console.WriteLine(peHeader1.ImageNtHeaders.OptionalHeader.DllCharacteristics);

            byte[] bytes = BitConverter.GetBytes(peHeader1.ImageNtHeaders.OptionalHeader.DllCharacteristics);

            int bitPos = 0;
            while (bitPos < 8 * bytes.Length)
            {
                int byteIndex = bitPos / 8;
                int offset = bitPos % 8;
                bool isSet = (bytes[byteIndex] & (1 << offset)) != 0;    

                Console.WriteLine(isSet);

                bitPos++;
            }

            Console.ReadKey();
        }
    }
}

Solution

  • I'm not sure I fully understand your problem, but here goes:

    PeNet has an enum that looks like this:

    [Flags]
    enum OptionalHeaderDllCharacteristics : ushort
    {
      IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE,
      IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY,
      IMAGE_DLLCHARACTERISTICS_NO_BIND,
      IMAGE_DLLCHARACTERISTICS_NO_ISOLATION,
      IMAGE_DLLCHARACTERISTICS_NO_SEH,
      IMAGE_DLLCHARACTERISTICS_NX_COMPAT,
      IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE,
      IMAGE_DLLCHARACTERISTICS_WDM_DRIVER,
    }
    

    You're somehow getting a value. That value must be cast to the enum:

    Int16 value = 3; //This is the value you got somewhere
    OptionalHeaderDllCharacteristics testEnum = (OptionalHeaderDllCharacteristics)value; //Cast it
    

    Once you've cast it you can test for any flag you desire:

    if (testEnum.HasFlag(OptionalHeaderDllCharacteristics.IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY))
    {
      //Do something
    }