[C#] 64 Bit DLL Mapping

Discussion in 'Mixed Languages' started by CODYQX4, May 23, 2013.

  1. CODYQX4

    CODYQX4 MDL Developer

    Sep 4, 2009
    4,813
    45,450
    150
    I am working on loading KMS-HGM from memory without a file, and I have it working, but only for x86, not x64 or AnyCPU.

    I need to compile a console app as AnyCPU, and I have two different DLLs embedded as resources (64 Bit would use the 64-Bit DLL).

    The code fails on x64 and says attempted to read or write protected memory, I think it may be due to differences in 64 bit processes.

    I need MTK to be AnyCPU, and am in the same boat with vbc.exe. This code is cleaner and simpler, and using a DLL would mean no external process, which is an improvement.

    Here is the code, I could use help adapting this to run as x64/AnyCPU.
    KMSLibrary.7z
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  2. Josh Cell

    Josh Cell MDL Developer

    Jan 8, 2011
    3,519
    7,112
    120
    #2 Josh Cell, May 23, 2013
    Last edited: May 23, 2013
    The x86 memory areas really are not the same from x64, so your code will not work because it is writing the module in another memory block.

    You need to convert the code making the write area x2. You can see it on IntPtr.Size that is 4 for x86 and 8 for x64. You just will need what are the blocks to convert while the process is x64. Just math it and see the results.
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  3. CODYQX4

    CODYQX4 MDL Developer

    Sep 4, 2009
    4,813
    45,450
    150
    I figured that was the case, but just how much of this code needs modded?
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  4. CODYQX4

    CODYQX4 MDL Developer

    Sep 4, 2009
    4,813
    45,450
    150
    #4 CODYQX4, May 24, 2013
    Last edited by a moderator: Apr 20, 2017
    (OP)
    Making huge breakthroughs so far.

    I copy pasted the code into 2 classes, mostly the same, but some of the structs for x64 are different.

    I'm getting an error here:
    Code:
    using System;
    using System.Runtime.InteropServices;
    
    namespace DLL64
    {
        public class DynamicDllLoader64
        {
            internal class Win32Constants
            {
                public static UInt32 MEM_COMMIT = 0x1000;
    
                public static UInt32 PAGE_EXECUTE_READWRITE = 0x40;
                public static UInt32 PAGE_READWRITE = 0x04;
    
                public static UInt32 MEM_RELEASE = 0x8000;
                public static UInt32 MEM_RESERVE = 0x2000;
    
            }
    
            internal static class Win32Imports
            {
                [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
                public static extern UInt32 GetProcAddress(IntPtr hModule, string procName);
    
                [DllImport("kernel32")]
                public static extern int LoadLibrary(string lpFileName);
    
                [DllImport("kernel32")]
                public static extern UInt32 GetLastError();
    
                [DllImport("kernel32.dll")]
                public static extern IntPtr GetProcAddress(IntPtr module, IntPtr ordinal);
    
                [DllImport("kernel32")]
                public static extern UInt32 VirtualAlloc(ulong lpStartAddr,
                     UInt32 size, UInt32 flAllocationType, UInt32 flProtect);
    
                [DllImport("kernel32.dll", SetLastError = true)]
                internal static extern bool VirtualFree(IntPtr lpAddress, UIntPtr dwSize,
                   uint dwFreeType);
    
                [DllImport("kernel32.dll", SetLastError = true)]
                internal static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize,
                   uint flNewProtect, out uint lpflOldProtect);
    
            }
            internal static class PointerHelpers
            {
                public static T ToStruct<T>(byte[] data) where T : struct
                {
                    unsafe
                    {
                        fixed (byte* p = &data[0])
                        {
                            return (T)Marshal.PtrToStructure(new IntPtr(p), typeof(T));
                        }
                    }
                }
    
                public static T ToStruct<T>(byte[] data, uint from) where T : struct
                {
                    unsafe
                    {
                        fixed (byte* p = &data[from])
                        {
                            return (T)Marshal.PtrToStructure(new IntPtr(p), typeof(T));
                        }
                    }
                }
    
                public static T ToStruct<T>(IntPtr ptr, uint from) where T : struct
                {
                    return (T)Marshal.PtrToStructure(ptr + (int)from, typeof(T));
                }
            }
    
            [UnmanagedFunctionPointer(CallingConvention.StdCall)]
            unsafe delegate bool fnDllEntry(int instance, uint reason, void* reserved);
    
            internal unsafe bool LoadLibrary(byte[] data)
            {
                //fnDllEntry dllEntry;
                var dosHeader = PointerHelpers.ToStruct<IMAGE_DOS_HEADER>(data);
    
                var oldHeader = PointerHelpers.ToStruct<IMAGE_NT_HEADERS>(data, (uint)dosHeader.e_lfanew);
    
                var code = (IntPtr)(Win32Imports.VirtualAlloc(oldHeader.OptionalHeader.ImageBase, oldHeader.OptionalHeader.SizeOfImage, Win32Constants.MEM_RESERVE, Win32Constants.PAGE_READWRITE));
    
                if (code.ToInt64() == 0)
                    code = (IntPtr)(Win32Imports.VirtualAlloc((uint)code, oldHeader.OptionalHeader.SizeOfImage, Win32Constants.MEM_RESERVE, Win32Constants.PAGE_READWRITE));
    
                module = new MEMORYMODULE { codeBase = code, numModules = 0, modules = new IntPtr(0), initialized = 0 };
    
                Win32Imports.VirtualAlloc((ulong)code, oldHeader.OptionalHeader.SizeOfImage, Win32Constants.MEM_COMMIT, Win32Constants.PAGE_READWRITE);
    
                var headers = (IntPtr)(Win32Imports.VirtualAlloc((ulong)code, oldHeader.OptionalHeader.SizeOfHeaders, Win32Constants.MEM_COMMIT, Win32Constants.PAGE_READWRITE));
    
                // TODO: Fails
                Marshal.Copy(data, 0, headers, (int)(dosHeader.e_lfanew + oldHeader.OptionalHeader.SizeOfHeaders));
    
                module.headers = PointerHelpers.ToStruct<IMAGE_NT_HEADERS>(headers, (uint)dosHeader.e_lfanew);
                module.headers.OptionalHeader.ImageBase = (uint)code;
    
                CopySections(data, oldHeader, headers, dosHeader);
    
                var locationDelta = (uint)(code - (int)oldHeader.OptionalHeader.ImageBase);
    
                if (locationDelta != 0)
                    PerformBaseRelocation(locationDelta);
    
                BuildImportTable();
                FinalizeSections(headers, dosHeader, oldHeader);
    
                bool success = false;
    
                try
                {
                    fnDllEntry dllEntry =
                        (fnDllEntry)
                        Marshal.GetDelegateForFunctionPointer(
                            new IntPtr(module.codeBase.ToInt32() + (int)module.headers.OptionalHeader.AddressOfEntryPoint),
                            typeof(fnDllEntry));
                    success = dllEntry(code.ToInt32(), 1, (void*)0);
                }
                catch (Exception ex)
                {
                    return false;
                }
                return success;
            }
    
            public int GetModuleCount()
            {
                int count = 0;
                IntPtr codeBase = module.codeBase;
                IMAGE_DATA_DIRECTORY directory = module.headers.OptionalHeader.DataDirectory[1];
                if (directory.Size > 0)
                {
                    var importDesc = PointerHelpers.ToStruct<IMAGE_IMPORT_DESCRIPTOR>(codeBase, directory.VirtualAddress);
                    while (importDesc.Name > 0)
                    {
                        var str = codeBase + (int)importDesc.Name;
                        string tmp = Marshal.PtrToStringAnsi(str);
                        int handle = Win32Imports.LoadLibrary(tmp);
    
                        if (handle == -1)
                        {
                            break;
                        }
                        count++;
                        importDesc = PointerHelpers.ToStruct<IMAGE_IMPORT_DESCRIPTOR>(codeBase, (uint)(directory.VirtualAddress + (Marshal.SizeOf(typeof(IMAGE_IMPORT_DESCRIPTOR)) * (count))));
                    }
                }
                return count;
            }
    
            public int BuildImportTable()
            {
                int ucount = GetModuleCount();
                module.modules = Marshal.AllocHGlobal((ucount) * sizeof(int));
                int pcount = 0;
                int result = 1;
                IntPtr codeBase = module.codeBase;
                IMAGE_DATA_DIRECTORY directory = module.headers.OptionalHeader.DataDirectory[1];
                if (directory.Size > 0)
                {
                    var importDesc = PointerHelpers.ToStruct<IMAGE_IMPORT_DESCRIPTOR>(codeBase, directory.VirtualAddress);
                    while (importDesc.Name > 0)
                    {
                        var str = codeBase + (int)importDesc.Name;
                        string tmp = Marshal.PtrToStringAnsi(str);
                        unsafe
                        {
                            uint* thunkRef;
                            uint* funcRef;
    
                            int handle = Win32Imports.LoadLibrary(tmp);
    
                            if (handle == -1)
                            {
                                result = 0;
                                break;
                            }
    
                            if (importDesc.CharacteristicsOrOriginalFirstThunk > 0)
                            {
                                IntPtr thunkRefAddr = codeBase + (int)importDesc.CharacteristicsOrOriginalFirstThunk;
                                thunkRef = (uint*)thunkRefAddr;
                                funcRef = (uint*)(codeBase + (int)importDesc.FirstThunk);
                            }
                            else
                            {
                                thunkRef = (uint*)(codeBase + (int)importDesc.FirstThunk);
                                funcRef = (uint*)(codeBase + (int)importDesc.FirstThunk);
                            }
                            for (; *thunkRef > 0; thunkRef++, funcRef++)
                            {
                                if ((*thunkRef & 0x80000000) != 0)
                                {
                                    *funcRef = (uint)Win32Imports.GetProcAddress(new IntPtr(handle), new IntPtr(*thunkRef & 0xffff));
                                }
                                else
                                {
                                    var str2 = codeBase + (int)(*thunkRef) + 2;
                                    var tmpaa = Marshal.PtrToStringAnsi(str2);
                                    *funcRef = Win32Imports.GetProcAddress(new IntPtr(handle), tmpaa);
                                }
                                if (*funcRef == 0)
                                {
                                    result = 0;
                                    break;
                                }
                            }
    
    
                            pcount++;
                            importDesc = PointerHelpers.ToStruct<IMAGE_IMPORT_DESCRIPTOR>(codeBase, directory.VirtualAddress + (uint)(Marshal.SizeOf(typeof(IMAGE_IMPORT_DESCRIPTOR)) * pcount));
                        }
                    }
                }
                return result;
            }
    
            static readonly int[][][] ProtectionFlags = new int[2][][];
    
            public void FinalizeSections(IntPtr headers, IMAGE_DOS_HEADER dosHeader, IMAGE_NT_HEADERS oldHeaders)
            {
                ProtectionFlags[0] = new int[2][];
                ProtectionFlags[1] = new int[2][];
                ProtectionFlags[0][0] = new int[2];
                ProtectionFlags[0][1] = new int[2];
                ProtectionFlags[1][0] = new int[2];
                ProtectionFlags[1][1] = new int[2];
                ProtectionFlags[0][0][0] = 0x01;
                ProtectionFlags[0][0][1] = 0x08;
                ProtectionFlags[0][1][0] = 0x02;
                ProtectionFlags[0][1][1] = 0x04;
                ProtectionFlags[1][0][0] = 0x10;
                ProtectionFlags[1][0][1] = 0x80;
                ProtectionFlags[1][1][0] = 0x20;
                ProtectionFlags[1][1][1] = 0x40;
    
                var section = PointerHelpers.ToStruct<IMAGE_SECTION_HEADER>(headers, (uint)(24 + dosHeader.e_lfanew + oldHeaders.FileHeader.SizeOfOptionalHeader));
                for (int i = 0; i < module.headers.FileHeader.NumberOfSections; i++)
                {
                    //Console.WriteLine("Finalizing " + Encoding.UTF8.GetString(section.Name));
                    int executable = (section.Characteristics & 0x20000000) != 0 ? 1 : 0;
                    int readable = (section.Characteristics & 0x40000000) != 0 ? 1 : 0;
                    int writeable = (section.Characteristics & 0x80000000) != 0 ? 1 : 0;
    
                    if ((section.Characteristics & 0x02000000) > 0)
                    {
                        bool aa = Win32Imports.VirtualFree(new IntPtr(section.PhysicalAddress), (UIntPtr)section.SizeOfRawData, 0x4000);
                        continue;
                    }
    
                    var protect = (uint)ProtectionFlags[executable][readable][writeable];
    
                    if ((section.Characteristics & 0x04000000) > 0)
                        protect |= 0x200;
                    var size = (int)section.SizeOfRawData;
                    if (size == 0)
                    {
                        if ((section.Characteristics & 0x00000040) > 0)
                            size = (int)module.headers.OptionalHeader.SizeOfInitializedData;
                        else if ((section.Characteristics & 0x00000080) > 0)
                            size = (int)module.headers.OptionalHeader.SizeOfUninitializedData;
    
                    }
    
                    if (size > 0)
                    {
                        uint oldProtect;
                        if (!Win32Imports.VirtualProtect(new IntPtr(section.PhysicalAddress), section.SizeOfRawData, protect, out oldProtect))
                        {
                        }
                    }
    
                    section = PointerHelpers.ToStruct<IMAGE_SECTION_HEADER>(headers, (uint)((24 + dosHeader.e_lfanew + oldHeaders.FileHeader.SizeOfOptionalHeader) + (Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER)) * (i + 1))));
                }
    
            }
    
            public void PerformBaseRelocation(uint delta)
            {
                IntPtr codeBase = module.codeBase;
                int sizeOfBase = Marshal.SizeOf(typeof(IMAGE_BASE_RELOCATION));
                IMAGE_DATA_DIRECTORY directory = module.headers.OptionalHeader.DataDirectory[5];
                int cnt = 0;
                if (directory.Size > 0)
                {
                    var relocation = PointerHelpers.ToStruct<IMAGE_BASE_RELOCATION>(codeBase, directory.VirtualAddress);
                    while (relocation.VirtualAddress > 0)
                    {
                        unsafe
                        {
                            var dest = (IntPtr)(codeBase.ToInt32() + (int)relocation.VirtualAddress);
                            var relInfo = (ushort*)(codeBase.ToInt32() + (int)directory.VirtualAddress + sizeOfBase);
                            uint i;
                            for (i = 0; i < ((relocation.SizeOfBlock - Marshal.SizeOf(typeof(IMAGE_BASE_RELOCATION))) / 2); i++, relInfo++)
                            {
                                int type = *relInfo >> 12;
                                int offset = (*relInfo & 0xfff);
                                switch (type)
                                {
                                    case 0x00:
                                        break;
                                    case 0x03:
                                        var patchAddrHl = (uint*)((dest) + (offset));
                                        *patchAddrHl += delta;
                                        break;
                                }
                            }
                        }
                        cnt += (int)relocation.SizeOfBlock;
                        relocation = PointerHelpers.ToStruct<IMAGE_BASE_RELOCATION>(codeBase, (uint)(directory.VirtualAddress + cnt));
    
                    }
                }
            }
    
            private MEMORYMODULE module;
            public uint GetProcAddress(string name)
            {
                unsafe
                {
                    IntPtr codeBase = module.codeBase;
                    int idx = -1;
                    uint i;
                    IMAGE_DATA_DIRECTORY directory = module.headers.OptionalHeader.DataDirectory[0];
                    if (directory.Size == 0)
                        return 0;
                    var exports = PointerHelpers.ToStruct<IMAGE_EXPORT_DIRECTORY>(codeBase, directory.VirtualAddress);
                    var nameRef = (uint*)new IntPtr(codeBase.ToInt32() + exports.AddressOfNames);
                    var ordinal = (ushort*)new IntPtr(codeBase.ToInt32() + exports.AddressOfNameOrdinals);
                    for (i = 0; i < exports.NumberOfNames; i++, nameRef++, ordinal++)
                    {
                        var str = codeBase + (int)(*nameRef);
                        string tmp = Marshal.PtrToStringAnsi(str);
                        if (tmp == name)
                        {
                            idx = *ordinal;
                            break;
                        }
                    }
    
                    var tmpaa = (uint*)(codeBase.ToInt32() + (exports.AddressOfFunctions + (idx * 4)));
                    var addr = (uint)((codeBase.ToInt32()) + (*tmpaa));
                    return addr;
                }
            }
    
            public void CopySections(byte[] data, IMAGE_NT_HEADERS oldHeaders, IntPtr headers, IMAGE_DOS_HEADER dosHeader)
            {
                int i;
                IntPtr codebase = module.codeBase;
                var section = PointerHelpers.ToStruct<IMAGE_SECTION_HEADER>(headers, (uint)(24 + dosHeader.e_lfanew + oldHeaders.FileHeader.SizeOfOptionalHeader));
                for (i = 0; i < module.headers.FileHeader.NumberOfSections; i++)
                {
                    IntPtr dest;
                    if (section.SizeOfRawData == 0)
                    {
                        uint size = oldHeaders.OptionalHeader.SectionAlignment;
                        if (size > 0)
                        {
                            dest = new IntPtr((Win32Imports.VirtualAlloc((uint)(codebase + (int)section.VirtualAddress), size, Win32Constants.MEM_COMMIT,
                                                         Win32Constants.PAGE_READWRITE)));
    
                            section.PhysicalAddress = (uint)dest;
                            var write = new IntPtr(headers.ToInt32() + (32 + dosHeader.e_lfanew + oldHeaders.FileHeader.SizeOfOptionalHeader) + (Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER)) * (i)));
                            Marshal.WriteInt32(write, (int)dest);
                            var datazz = new byte[size + 1];
                            Marshal.Copy(datazz, 0, dest, (int)size);
                        }
                        section = PointerHelpers.ToStruct<IMAGE_SECTION_HEADER>(headers, (uint)((24 + dosHeader.e_lfanew + oldHeaders.FileHeader.SizeOfOptionalHeader) + (Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER)) * (i + 1))));
                        continue;
                    }
    
                    dest = new IntPtr((Win32Imports.VirtualAlloc((uint)(codebase + (int)section.VirtualAddress), section.SizeOfRawData, Win32Constants.MEM_COMMIT,
                                                 Win32Constants.PAGE_READWRITE)));
                    Marshal.Copy(data, (int)section.PointerToRawData, dest, (int)section.SizeOfRawData);
                    section.PhysicalAddress = (uint)dest;
                    var write2 = new IntPtr(headers.ToInt32() + (32 + dosHeader.e_lfanew + oldHeaders.FileHeader.SizeOfOptionalHeader) + (Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER)) * (i)));
                    Marshal.WriteInt32(write2, (int)dest);
                    section = PointerHelpers.ToStruct<IMAGE_SECTION_HEADER>(headers, (uint)((24 + dosHeader.e_lfanew + oldHeaders.FileHeader.SizeOfOptionalHeader) + (Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER)) * (i + 1))));
                }
            }
        }
    
        [StructLayout(LayoutKind.Sequential)]
        public struct IMAGE_EXPORT_DIRECTORY
        {
            public UInt32 Characteristics;
            public UInt32 TimeDateStamp;
            public UInt16 MajorVersion;
            public UInt16 MinorVersion;
            public UInt32 Name;
            public UInt32 Base;
            public UInt32 NumberOfFunctions;
            public UInt32 NumberOfNames;
            public UInt32 AddressOfFunctions;     // RVA from base of image
            public UInt32 AddressOfNames;     // RVA from base of image
            public UInt32 AddressOfNameOrdinals;  // RVA from base of image
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct IMAGE_IMPORT_BY_NAME
        {
            public short Hint;
            public byte Name;
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct MEMORYMODULE
        {
            public IMAGE_NT_HEADERS headers;
            public IntPtr codeBase;
            public IntPtr modules;
            public int numModules;
            public int initialized;
    
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct IMAGE_BASE_RELOCATION
        {
            public uint VirtualAddress;
            public uint SizeOfBlock;
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct IMAGE_IMPORT_DESCRIPTOR
        {
            public uint CharacteristicsOrOriginalFirstThunk;    // 0 for terminating null import descriptor; RVA to original unbound IAT (PIMAGE_THUNK_DATA)
            public uint TimeDateStamp;                          // 0 if not bound, -1 if bound, and real date\time stamp in IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT (new BIND); O.W. date/time stamp of DLL bound to (Old BIND)
            public uint ForwarderChain;                         // -1 if no forwarders
            public uint Name;
            public uint FirstThunk;                             // RVA to IAT (if bound this IAT has actual addresses)
        }
    
        [StructLayout(LayoutKind.Sequential, Pack = 4)]
        public struct IMAGE_SECTION_HEADER
        {
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
            public byte[] Name;
            //union 
            //{    
            //    DWORD PhysicalAddress;    
            //    DWORD VirtualSize;  
            //} Misc;  
            public uint PhysicalAddress;
            //public uint VirtualSize;
            public uint VirtualAddress;
            public uint SizeOfRawData;
            public uint PointerToRawData;
            public uint PointerToRelocations;
            public uint PointerToLinenumbers;
            public short NumberOfRelocations;
            public short NumberOfLinenumbers;
            public uint Characteristics;
        }
        [StructLayout(LayoutKind.Sequential, Pack = 4)]
        public unsafe struct IMAGE_DOS_HEADER
        {
            public UInt16 e_magic;       // Magic number
            public UInt16 e_cblp;        // Bytes on last page of file
            public UInt16 e_cp;          // Pages in file
            public UInt16 e_crlc;        // Relocations
            public UInt16 e_cparhdr;     // Size of header in paragraphs
            public UInt16 e_minalloc;    // Minimum extra paragraphs needed
            public UInt16 e_maxalloc;    // Maximum extra paragraphs needed
            public UInt16 e_ss;          // Initial (relative) SS value
            public UInt16 e_sp;          // Initial SP value
            public UInt16 e_csum;        // Checksum
            public UInt16 e_ip;          // Initial IP value
            public UInt16 e_cs;          // Initial (relative) CS value
            public UInt16 e_lfarlc;      // File address of relocation table
            public UInt16 e_ovno;        // Overlay number
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
            public UInt16[] e_res1;        // Reserved words
            public UInt16 e_oemid;       // OEM identifier (for e_oeminfo)
            public UInt16 e_oeminfo;     // OEM information; e_oemid specific
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
            public UInt16[] e_res2;        // Reserved words
            public Int32 e_lfanew;      // File address of new exe header
        }
        [StructLayout(LayoutKind.Sequential, Pack = 4)]
        public struct IMAGE_DATA_DIRECTORY
        {
            public UInt32 VirtualAddress;
            public UInt32 Size;
        }
        [StructLayout(LayoutKind.Sequential, Pack = 4)]
        public struct IMAGE_OPTIONAL_HEADER64
        {
            //
            // Standard fields.
            //
            public UInt16 Magic;
            public Byte MajorLinkerVersion;
            public Byte MinorLinkerVersion;
            public UInt32 SizeOfCode;
            public UInt32 SizeOfInitializedData;
            public UInt32 SizeOfUninitializedData;
            public UInt32 AddressOfEntryPoint;
            public UInt32 BaseOfCode;
            //
            // NT additional fields.
            //
            public UInt64 ImageBase;
            public UInt32 SectionAlignment;
            public UInt32 FileAlignment;
            public UInt16 MajorOperatingSystemVersion;
            public UInt16 MinorOperatingSystemVersion;
            public UInt16 MajorImageVersion;
            public UInt16 MinorImageVersion;
            public UInt16 MajorSubsystemVersion;
            public UInt16 MinorSubsystemVersion;
            public UInt32 Win32VersionValue;
            public UInt32 SizeOfImage;
            public UInt32 SizeOfHeaders;
            public UInt32 CheckSum;
            public UInt16 Subsystem;
            public UInt16 DllCharacteristics;
            public UInt64 SizeOfStackReserve;
            public UInt64 SizeOfStackCommit;
            public UInt64 SizeOfHeapReserve;
            public UInt64 SizeOfHeapCommit;
            public UInt32 LoaderFlags;
            public UInt32 NumberOfRvaAndSizes;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
            public IMAGE_DATA_DIRECTORY[] DataDirectory;
        }
        [StructLayout(LayoutKind.Sequential, Pack = 4)]
        public struct IMAGE_FILE_HEADER
        {
            public UInt16 Machine;
            public UInt16 NumberOfSections;
            public UInt32 TimeDateStamp;
            public UInt32 PointerToSymbolTable;
            public UInt32 NumberOfSymbols;
            public UInt16 SizeOfOptionalHeader;
            public UInt16 Characteristics;
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct IMAGE_NT_HEADERS
        {
            public UInt32 Signature;
            public IMAGE_FILE_HEADER FileHeader;
            public IMAGE_OPTIONAL_HEADER64 OptionalHeader;
        }
    }
    
    See the // TODO: Fails line?

    This gives the following error:
    Code:
    Unhandled Exception: System.ArgumentNullException: Value cannot be null.
    Parameter name: destination
       at System.Runtime.InteropServices.Marshal.CopyToNative(Object source, Int32 s
    tartIndex, IntPtr destination, Int32 length)
       at DLL64.DynamicDllLoader64.LoadLibrary(Byte[] data) in i:\My Data\My Source
    Code\C#\Projects\Visual Studio\KMSLibrary\DynamicDllLoader64.cs:line 98
       at KMSLibrary.Program.Main() in i:\My Data\My Source Code\C#\Projects\Visual
    Studio\KMSLibrary\Program.cs:line 82
    
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  5. PAYMYRENT

    PAYMYRENT MDL Developer

    Jul 28, 2009
    1,462
    419
    60
    #5 PAYMYRENT, May 24, 2013
    Last edited: May 24, 2013
    Have you tried taking a look at how the VB.NET RunPE code works? You are trying to recreate it will what you are doing here - basic image injection -- http://pastebin.com/jSNyuc08

    EDIT: This might even suite your needs better - This is the C++ RunPE - I have used this before and it works for both x86 files and x64 files

    http://pastebin.com/8QMupfQg

    EDIT2: Even better this is the C# one - Untested but still the basics of loading up files

    http://pastebin.com/7Maq937s
     
  6. CODYQX4

    CODYQX4 MDL Developer

    Sep 4, 2009
    4,813
    45,450
    150
    This is a little different than RunPE, which I used to use, and which didn't work on x64.

    This is loading DLLs. Anyway, as I fix errors, it seems I can step through line by line until it stops failing, but I haven't figured out how to fix that line I marked.

    PS: Are you sure that C# RunPE works on x64? Because I've wanted one that does.
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  7. PAYMYRENT

    PAYMYRENT MDL Developer

    Jul 28, 2009
    1,462
    419
    60
    Not sure about the C# one but I know the vb.net and C++ ones works - Needed it for my software protection methods
     
  8. CODYQX4

    CODYQX4 MDL Developer

    Sep 4, 2009
    4,813
    45,450
    150
    Well if worst comes to worst, VB.NET will run just fine inside a DLL as a separate library since .NET doesn't care what language you compile with.

    If I compile a DLL using the VB.NET code as AnyCPU, it will work?
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  9. PAYMYRENT

    PAYMYRENT MDL Developer

    Jul 28, 2009
    1,462
    419
    60
    To be honest - I have never tried anycpu with it ... just plain x86 .. and x64.. I can reboot and test real quick lol
     
  10. qad

    qad MDL Member

    Dec 17, 2012
    218
    826
    10
    #10 qad, May 26, 2013
    Last edited: May 26, 2013
    @CODYQX4

    I managed to get AnyCPU build working.
    KMSLibrary.7z

    Basically, I changed the pointer arithmetics to fit 64bit and the basic functionality seems to be working.
    One thing that I couldn't test is the 64bit relocation because the DLL is always mapped at original ImageBase in my tests.
    I hope this helps you.

    P.S
    I also changed the way of marshalling Request/Response in KMS.cs so that they use built-in MarshalAs like DllLoader.
    If you don't want them, please just use DynamicDllLoader.cs only and adjust Main func in Program.cs.

    P.S 2
    I refer this repo what is needed to make it work for x64.

    Regard.
     
  11. CODYQX4

    CODYQX4 MDL Developer

    Sep 4, 2009
    4,813
    45,450
    150
    Testing as x86, x64, and AnyCPU all work fine.
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  12. Josh Cell

    Josh Cell MDL Developer

    Jan 8, 2011
    3,519
    7,112
    120
    Yeah, nice work.

    That's like I have looked in a first moment inside the thread.
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...