├── DynamicDLLLoader.sln
├── DynamicDLLLoader
├── DynamicDLLLoader.csproj
├── DynamicDllLoader.cs
├── Program.cs
└── Properties
│ └── AssemblyInfo.cs
└── README.md
/DynamicDLLLoader.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DynamicDLLLoader", "DynamicDLLLoader\DynamicDLLLoader.csproj", "{0D19247E-FE11-4F0D-915D-6CA1921A7542}"
4 | EndProject
5 | Global
6 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
7 | Debug|Any CPU = Debug|Any CPU
8 | Release|Any CPU = Release|Any CPU
9 | EndGlobalSection
10 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
11 | {0D19247E-FE11-4F0D-915D-6CA1921A7542}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
12 | {0D19247E-FE11-4F0D-915D-6CA1921A7542}.Debug|Any CPU.Build.0 = Debug|Any CPU
13 | {0D19247E-FE11-4F0D-915D-6CA1921A7542}.Release|Any CPU.ActiveCfg = Release|Any CPU
14 | {0D19247E-FE11-4F0D-915D-6CA1921A7542}.Release|Any CPU.Build.0 = Release|Any CPU
15 | EndGlobalSection
16 | EndGlobal
17 |
--------------------------------------------------------------------------------
/DynamicDLLLoader/DynamicDLLLoader.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {0D19247E-FE11-4F0D-915D-6CA1921A7542}
8 | Exe
9 | Properties
10 | DynamicDLLLoader
11 | DynamicDLLLoader
12 | v4.6.1
13 | 512
14 |
15 |
16 | AnyCPU
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 | true
25 |
26 |
27 | AnyCPU
28 | pdbonly
29 | true
30 | bin\Release\
31 | TRACE
32 | prompt
33 | 4
34 | true
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/DynamicDLLLoader/DynamicDllLoader.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.InteropServices;
3 |
4 | namespace DynamicDLLLoader
5 | {
6 | public class DynamicDllLoader
7 | {
8 | [StructLayout(LayoutKind.Sequential)]
9 | public struct IMAGE_EXPORT_DIRECTORY
10 | {
11 | public UInt32 Characteristics;
12 | public UInt32 TimeDateStamp;
13 | public UInt16 MajorVersion;
14 | public UInt16 MinorVersion;
15 | public UInt32 Name;
16 | public UInt32 Base;
17 | public UInt32 NumberOfFunctions;
18 | public UInt32 NumberOfNames;
19 | public UInt32 AddressOfFunctions; // RVA from base of image
20 | public UInt32 AddressOfNames; // RVA from base of image
21 | public UInt32 AddressOfNameOrdinals; // RVA from base of image
22 | }
23 |
24 | [StructLayout(LayoutKind.Sequential)]
25 | public struct IMAGE_IMPORT_BY_NAME
26 | {
27 | public short Hint;
28 | public byte Name;
29 | }
30 |
31 | [StructLayout(LayoutKind.Sequential)]
32 | public struct MEMORYMODULE
33 | {
34 | public IMAGE_NT_HEADERS headers;
35 | public IntPtr codeBase;
36 | public IntPtr modules;
37 | public int numModules;
38 | public int initialized;
39 | }
40 |
41 | [StructLayout(LayoutKind.Sequential)]
42 | public struct IMAGE_BASE_RELOCATION
43 | {
44 | public uint VirtualAddress;
45 | public uint SizeOfBlock;
46 | }
47 |
48 | [StructLayout(LayoutKind.Sequential)]
49 | public struct IMAGE_IMPORT_DESCRIPTOR
50 | {
51 | public uint
52 | CharacteristicsOrOriginalFirstThunk; // 0 for terminating null import descriptor; RVA to original unbound IAT (PIMAGE_THUNK_DATA)
53 |
54 | public uint
55 | 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)
56 |
57 | public uint ForwarderChain; // -1 if no forwarders
58 | public uint Name;
59 | public uint FirstThunk; // RVA to IAT (if bound this IAT has actual addresses)
60 | }
61 |
62 | [StructLayout(LayoutKind.Sequential, Pack = 4)]
63 | public struct IMAGE_SECTION_HEADER
64 | {
65 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
66 | public byte[] Name;
67 |
68 | //union
69 | //{
70 | // DWORD PhysicalAddress;
71 | // DWORD VirtualSize;
72 | //} Misc;
73 | public uint PhysicalAddress;
74 |
75 | //public uint VirtualSize;
76 | public uint VirtualAddress;
77 | public uint SizeOfRawData;
78 | public uint PointerToRawData;
79 | public uint PointerToRelocations;
80 | public uint PointerToLinenumbers;
81 | public short NumberOfRelocations;
82 | public short NumberOfLinenumbers;
83 | public uint Characteristics;
84 | }
85 |
86 | [StructLayout(LayoutKind.Sequential, Pack = 4)]
87 | public unsafe struct IMAGE_DOS_HEADER
88 | {
89 | public UInt16 e_magic; // Magic number
90 | public UInt16 e_cblp; // Bytes on last page of file
91 | public UInt16 e_cp; // Pages in file
92 | public UInt16 e_crlc; // Relocations
93 | public UInt16 e_cparhdr; // Size of header in paragraphs
94 | public UInt16 e_minalloc; // Minimum extra paragraphs needed
95 | public UInt16 e_maxalloc; // Maximum extra paragraphs needed
96 | public UInt16 e_ss; // Initial (relative) SS value
97 | public UInt16 e_sp; // Initial SP value
98 | public UInt16 e_csum; // Checksum
99 | public UInt16 e_ip; // Initial IP value
100 | public UInt16 e_cs; // Initial (relative) CS value
101 | public UInt16 e_lfarlc; // File address of relocation table
102 | public UInt16 e_ovno; // Overlay number
103 |
104 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
105 | public UInt16[] e_res1; // Reserved words
106 |
107 | public UInt16 e_oemid; // OEM identifier (for e_oeminfo)
108 | public UInt16 e_oeminfo; // OEM information; e_oemid specific
109 |
110 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
111 | public UInt16[] e_res2; // Reserved words
112 |
113 | public Int32 e_lfanew; // File address of new exe header
114 | }
115 |
116 | [StructLayout(LayoutKind.Sequential, Pack = 4)]
117 | public struct IMAGE_DATA_DIRECTORY
118 | {
119 | public UInt32 VirtualAddress;
120 | public UInt32 Size;
121 | }
122 |
123 | [StructLayout(LayoutKind.Sequential, Pack = 4)]
124 | public struct IMAGE_OPTIONAL_HEADER32
125 | {
126 | //
127 | // Standard fields.
128 | //
129 | public UInt16 Magic;
130 | public Byte MajorLinkerVersion;
131 | public Byte MinorLinkerVersion;
132 | public UInt32 SizeOfCode;
133 | public UInt32 SizeOfInitializedData;
134 | public UInt32 SizeOfUninitializedData;
135 | public UInt32 AddressOfEntryPoint;
136 | public UInt32 BaseOfCode;
137 |
138 | public UInt32 BaseOfData;
139 |
140 | //
141 | // NT additional fields.
142 | //
143 | public UInt32 ImageBase;
144 | public UInt32 SectionAlignment;
145 | public UInt32 FileAlignment;
146 | public UInt16 MajorOperatingSystemVersion;
147 | public UInt16 MinorOperatingSystemVersion;
148 | public UInt16 MajorImageVersion;
149 | public UInt16 MinorImageVersion;
150 | public UInt16 MajorSubsystemVersion;
151 | public UInt16 MinorSubsystemVersion;
152 | public UInt32 Win32VersionValue;
153 | public UInt32 SizeOfImage;
154 | public UInt32 SizeOfHeaders;
155 | public UInt32 CheckSum;
156 | public UInt16 Subsystem;
157 | public UInt16 DllCharacteristics;
158 | public UInt32 SizeOfStackReserve;
159 | public UInt32 SizeOfStackCommit;
160 | public UInt32 SizeOfHeapReserve;
161 | public UInt32 SizeOfHeapCommit;
162 | public UInt32 LoaderFlags;
163 | public UInt32 NumberOfRvaAndSizes;
164 |
165 | [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
166 | public IMAGE_DATA_DIRECTORY[] DataDirectory;
167 | }
168 |
169 | [StructLayout(LayoutKind.Sequential, Pack = 4)]
170 | public struct IMAGE_FILE_HEADER
171 | {
172 | public UInt16 Machine;
173 | public UInt16 NumberOfSections;
174 | public UInt32 TimeDateStamp;
175 | public UInt32 PointerToSymbolTable;
176 | public UInt32 NumberOfSymbols;
177 | public UInt16 SizeOfOptionalHeader;
178 | public UInt16 Characteristics;
179 | }
180 |
181 | [StructLayout(LayoutKind.Sequential)]
182 | public struct IMAGE_NT_HEADERS
183 | {
184 | public UInt32 Signature;
185 | public IMAGE_FILE_HEADER FileHeader;
186 | public IMAGE_OPTIONAL_HEADER32 OptionalHeader;
187 | }
188 |
189 | internal class Win32Constants
190 | {
191 | public static UInt32 MEM_COMMIT = 0x1000;
192 |
193 | public static UInt32 PAGE_EXECUTE_READWRITE = 0x40;
194 | public static UInt32 PAGE_READWRITE = 0x04;
195 |
196 | public static UInt32 MEM_RELEASE = 0x8000;
197 | public static UInt32 MEM_RESERVE = 0x2000;
198 | }
199 |
200 | internal static class Win32Imports
201 | {
202 | [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
203 | public static extern UInt32 GetProcAddress(IntPtr hModule, string procName);
204 |
205 | [DllImport("kernel32")]
206 | public static extern int LoadLibrary(string lpFileName);
207 |
208 | [DllImport("kernel32")]
209 | public static extern UInt32 GetLastError();
210 |
211 | [DllImport("kernel32.dll")]
212 | public static extern IntPtr GetProcAddress(IntPtr module, IntPtr ordinal);
213 |
214 | [DllImport("kernel32")]
215 | public static extern UInt32 VirtualAlloc(UInt32 lpStartAddr,
216 | UInt32 size, UInt32 flAllocationType, UInt32 flProtect);
217 |
218 | [DllImport("kernel32.dll", SetLastError = true)]
219 | internal static extern bool VirtualFree(IntPtr lpAddress, UIntPtr dwSize,
220 | uint dwFreeType);
221 |
222 | [DllImport("kernel32.dll", SetLastError = true)]
223 | internal static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize,
224 | uint flNewProtect, out uint lpflOldProtect);
225 | }
226 |
227 | internal static class PointerHelpers
228 | {
229 | public static T ToStruct(byte[] data) where T : struct
230 | {
231 | unsafe
232 | {
233 | fixed (byte* p = &data[0])
234 | {
235 | return (T) Marshal.PtrToStructure(new IntPtr(p), typeof(T));
236 | }
237 | }
238 | }
239 |
240 | public static T ToStruct(byte[] data, uint from) where T : struct
241 | {
242 | unsafe
243 | {
244 | fixed (byte* p = &data[from])
245 | {
246 | return (T) Marshal.PtrToStructure(new IntPtr(p), typeof(T));
247 | }
248 | }
249 | }
250 |
251 | public static T ToStruct(IntPtr ptr, uint from) where T : struct
252 | {
253 | return (T) Marshal.PtrToStructure(ptr + (int) from, typeof(T));
254 | }
255 | }
256 |
257 | [UnmanagedFunctionPointer(CallingConvention.StdCall)]
258 | unsafe delegate bool fnDllEntry(int instance, uint reason, void* reserved);
259 |
260 | internal unsafe bool LoadLibrary(byte[] data)
261 | {
262 | //fnDllEntry dllEntry;
263 | var dosHeader = PointerHelpers.ToStruct(data);
264 |
265 | var oldHeader = PointerHelpers.ToStruct(data, (uint) dosHeader.e_lfanew);
266 |
267 | var code = (IntPtr) (Win32Imports.VirtualAlloc(oldHeader.OptionalHeader.ImageBase,
268 | oldHeader.OptionalHeader.SizeOfImage, Win32Constants.MEM_RESERVE, Win32Constants.PAGE_READWRITE));
269 |
270 | if (code.ToInt32() == 0)
271 | code = (IntPtr) (Win32Imports.VirtualAlloc((uint) code, oldHeader.OptionalHeader.SizeOfImage,
272 | Win32Constants.MEM_RESERVE, Win32Constants.PAGE_READWRITE));
273 |
274 | module = new MEMORYMODULE {codeBase = code, numModules = 0, modules = new IntPtr(0), initialized = 0};
275 |
276 | Win32Imports.VirtualAlloc((uint) code, oldHeader.OptionalHeader.SizeOfImage, Win32Constants.MEM_COMMIT,
277 | Win32Constants.PAGE_READWRITE);
278 |
279 | var headers = (IntPtr) (Win32Imports.VirtualAlloc((uint) code, oldHeader.OptionalHeader.SizeOfHeaders,
280 | Win32Constants.MEM_COMMIT, Win32Constants.PAGE_READWRITE));
281 |
282 | Marshal.Copy(data, 0, headers, (int) (dosHeader.e_lfanew + oldHeader.OptionalHeader.SizeOfHeaders));
283 |
284 | module.headers = PointerHelpers.ToStruct(headers, (uint) dosHeader.e_lfanew);
285 | module.headers.OptionalHeader.ImageBase = (uint) code;
286 |
287 | CopySections(data, oldHeader, headers, dosHeader);
288 |
289 | var locationDelta = (uint) (code - (int) oldHeader.OptionalHeader.ImageBase);
290 |
291 | if (locationDelta != 0)
292 | PerformBaseRelocation(locationDelta);
293 |
294 | BuildImportTable();
295 | FinalizeSections(headers, dosHeader, oldHeader);
296 |
297 | bool success = false;
298 |
299 | try
300 | {
301 | fnDllEntry dllEntry =
302 | (fnDllEntry)
303 | Marshal.GetDelegateForFunctionPointer(
304 | new IntPtr(module.codeBase.ToInt32() + (int) module.headers.OptionalHeader.AddressOfEntryPoint),
305 | typeof(fnDllEntry));
306 | success = dllEntry(code.ToInt32(), 1, (void*) 0);
307 | }
308 | catch (Exception ex)
309 | {
310 | return false;
311 | }
312 |
313 | return success;
314 | }
315 |
316 | public int GetModuleCount()
317 | {
318 | int count = 0;
319 | IntPtr codeBase = module.codeBase;
320 | IMAGE_DATA_DIRECTORY directory = module.headers.OptionalHeader.DataDirectory[1];
321 | if (directory.Size > 0)
322 | {
323 | var importDesc = PointerHelpers.ToStruct(codeBase, directory.VirtualAddress);
324 | while (importDesc.Name > 0)
325 | {
326 | var str = codeBase + (int) importDesc.Name;
327 | string tmp = Marshal.PtrToStringAnsi(str);
328 | int handle = Win32Imports.LoadLibrary(tmp);
329 |
330 | if (handle == -1)
331 | {
332 | break;
333 | }
334 |
335 | count++;
336 | importDesc = PointerHelpers.ToStruct(codeBase,
337 | (uint) (directory.VirtualAddress +
338 | (Marshal.SizeOf(typeof(IMAGE_IMPORT_DESCRIPTOR)) * (count))));
339 | }
340 | }
341 |
342 | return count;
343 | }
344 |
345 | public int BuildImportTable()
346 | {
347 | int ucount = GetModuleCount();
348 | module.modules = Marshal.AllocHGlobal((ucount) * sizeof(int));
349 | int pcount = 0;
350 | int result = 1;
351 | IntPtr codeBase = module.codeBase;
352 | IMAGE_DATA_DIRECTORY directory = module.headers.OptionalHeader.DataDirectory[1];
353 | if (directory.Size > 0)
354 | {
355 | var importDesc = PointerHelpers.ToStruct(codeBase, directory.VirtualAddress);
356 | while (importDesc.Name > 0)
357 | {
358 | var str = codeBase + (int) importDesc.Name;
359 | string tmp = Marshal.PtrToStringAnsi(str);
360 | unsafe
361 | {
362 | uint* thunkRef;
363 | uint* funcRef;
364 |
365 | int handle = Win32Imports.LoadLibrary(tmp);
366 |
367 | if (handle == -1)
368 | {
369 | result = 0;
370 | break;
371 | }
372 |
373 | if (importDesc.CharacteristicsOrOriginalFirstThunk > 0)
374 | {
375 | IntPtr thunkRefAddr = codeBase + (int) importDesc.CharacteristicsOrOriginalFirstThunk;
376 | thunkRef = (uint*) thunkRefAddr;
377 | funcRef = (uint*) (codeBase + (int) importDesc.FirstThunk);
378 | }
379 | else
380 | {
381 | thunkRef = (uint*) (codeBase + (int) importDesc.FirstThunk);
382 | funcRef = (uint*) (codeBase + (int) importDesc.FirstThunk);
383 | }
384 |
385 | for (; *thunkRef > 0; thunkRef++, funcRef++)
386 | {
387 | if ((*thunkRef & 0x80000000) != 0)
388 | {
389 | *funcRef = (uint) Win32Imports.GetProcAddress(new IntPtr(handle),
390 | new IntPtr(*thunkRef & 0xffff));
391 | }
392 | else
393 | {
394 | var str2 = codeBase + (int) (*thunkRef) + 2;
395 | var tmpaa = Marshal.PtrToStringAnsi(str2);
396 | *funcRef = Win32Imports.GetProcAddress(new IntPtr(handle), tmpaa);
397 | }
398 |
399 | if (*funcRef == 0)
400 | {
401 | result = 0;
402 | break;
403 | }
404 | }
405 |
406 |
407 | pcount++;
408 | importDesc = PointerHelpers.ToStruct(codeBase,
409 | directory.VirtualAddress +
410 | (uint) (Marshal.SizeOf(typeof(IMAGE_IMPORT_DESCRIPTOR)) * pcount));
411 | }
412 | }
413 | }
414 |
415 | return result;
416 | }
417 |
418 | static readonly int[][][] ProtectionFlags = new int[2][][];
419 |
420 | public void FinalizeSections(IntPtr headers, IMAGE_DOS_HEADER dosHeader, IMAGE_NT_HEADERS oldHeaders)
421 | {
422 | ProtectionFlags[0] = new int[2][];
423 | ProtectionFlags[1] = new int[2][];
424 | ProtectionFlags[0][0] = new int[2];
425 | ProtectionFlags[0][1] = new int[2];
426 | ProtectionFlags[1][0] = new int[2];
427 | ProtectionFlags[1][1] = new int[2];
428 | ProtectionFlags[0][0][0] = 0x01;
429 | ProtectionFlags[0][0][1] = 0x08;
430 | ProtectionFlags[0][1][0] = 0x02;
431 | ProtectionFlags[0][1][1] = 0x04;
432 | ProtectionFlags[1][0][0] = 0x10;
433 | ProtectionFlags[1][0][1] = 0x80;
434 | ProtectionFlags[1][1][0] = 0x20;
435 | ProtectionFlags[1][1][1] = 0x40;
436 |
437 | var section = PointerHelpers.ToStruct(headers,
438 | (uint) (24 + dosHeader.e_lfanew + oldHeaders.FileHeader.SizeOfOptionalHeader));
439 | for (int i = 0; i < module.headers.FileHeader.NumberOfSections; i++)
440 | {
441 | //Console.WriteLine("Finalizing " + Encoding.UTF8.GetString(section.Name));
442 | int executable = (section.Characteristics & 0x20000000) != 0 ? 1 : 0;
443 | int readable = (section.Characteristics & 0x40000000) != 0 ? 1 : 0;
444 | int writeable = (section.Characteristics & 0x80000000) != 0 ? 1 : 0;
445 |
446 | if ((section.Characteristics & 0x02000000) > 0)
447 | {
448 | bool aa = Win32Imports.VirtualFree(new IntPtr(section.PhysicalAddress),
449 | (UIntPtr) section.SizeOfRawData, 0x4000);
450 | continue;
451 | }
452 |
453 | var protect = (uint) ProtectionFlags[executable][readable][writeable];
454 |
455 | if ((section.Characteristics & 0x04000000) > 0)
456 | protect |= 0x200;
457 | var size = (int) section.SizeOfRawData;
458 | if (size == 0)
459 | {
460 | if ((section.Characteristics & 0x00000040) > 0)
461 | size = (int) module.headers.OptionalHeader.SizeOfInitializedData;
462 | else if ((section.Characteristics & 0x00000080) > 0)
463 | size = (int) module.headers.OptionalHeader.SizeOfUninitializedData;
464 | }
465 |
466 | if (size > 0)
467 | {
468 | uint oldProtect;
469 | if (!Win32Imports.VirtualProtect(new IntPtr(section.PhysicalAddress), section.SizeOfRawData,
470 | protect, out oldProtect))
471 | {
472 | }
473 | }
474 |
475 | section = PointerHelpers.ToStruct(headers,
476 | (uint) ((24 + dosHeader.e_lfanew + oldHeaders.FileHeader.SizeOfOptionalHeader) +
477 | (Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER)) * (i + 1))));
478 | }
479 | }
480 |
481 | public void PerformBaseRelocation(uint delta)
482 | {
483 | IntPtr codeBase = module.codeBase;
484 | int sizeOfBase = Marshal.SizeOf(typeof(IMAGE_BASE_RELOCATION));
485 | IMAGE_DATA_DIRECTORY directory = module.headers.OptionalHeader.DataDirectory[5];
486 | int cnt = 0;
487 | if (directory.Size > 0)
488 | {
489 | var relocation = PointerHelpers.ToStruct(codeBase, directory.VirtualAddress);
490 | while (relocation.VirtualAddress > 0)
491 | {
492 | unsafe
493 | {
494 | var dest = (IntPtr) (codeBase.ToInt32() + (int) relocation.VirtualAddress);
495 | var relInfo = (ushort*) (codeBase.ToInt32() + (int) directory.VirtualAddress + sizeOfBase);
496 | uint i;
497 | for (i = 0;
498 | i < ((relocation.SizeOfBlock - Marshal.SizeOf(typeof(IMAGE_BASE_RELOCATION))) / 2);
499 | i++, relInfo++)
500 | {
501 | int type = *relInfo >> 12;
502 | int offset = (*relInfo & 0xfff);
503 | switch (type)
504 | {
505 | case 0x00:
506 | break;
507 | case 0x03:
508 | var patchAddrHl = (uint*) ((dest) + (offset));
509 | *patchAddrHl += delta;
510 | break;
511 | }
512 | }
513 | }
514 |
515 | cnt += (int) relocation.SizeOfBlock;
516 | relocation =
517 | PointerHelpers.ToStruct(codeBase,
518 | (uint) (directory.VirtualAddress + cnt));
519 | }
520 | }
521 | }
522 |
523 | private MEMORYMODULE module;
524 |
525 | public uint GetProcAddress(string name)
526 | {
527 | unsafe
528 | {
529 | IntPtr codeBase = module.codeBase;
530 | int idx = -1;
531 | uint i;
532 | IMAGE_DATA_DIRECTORY directory = module.headers.OptionalHeader.DataDirectory[0];
533 | if (directory.Size == 0)
534 | return 0;
535 | var exports = PointerHelpers.ToStruct(codeBase, directory.VirtualAddress);
536 | var nameRef = (uint*) new IntPtr(codeBase.ToInt32() + exports.AddressOfNames);
537 | var ordinal = (ushort*) new IntPtr(codeBase.ToInt32() + exports.AddressOfNameOrdinals);
538 | for (i = 0; i < exports.NumberOfNames; i++, nameRef++, ordinal++)
539 | {
540 | var str = codeBase + (int) (*nameRef);
541 | string tmp = Marshal.PtrToStringAnsi(str);
542 | if (tmp == name)
543 | {
544 | idx = *ordinal;
545 | break;
546 | }
547 | }
548 |
549 | var tmpaa = (uint*) (codeBase.ToInt32() + (exports.AddressOfFunctions + (idx * 4)));
550 | var addr = (uint) ((codeBase.ToInt32()) + (*tmpaa));
551 | return addr;
552 | }
553 | }
554 |
555 | public void CopySections(byte[] data, IMAGE_NT_HEADERS oldHeaders, IntPtr headers, IMAGE_DOS_HEADER dosHeader)
556 | {
557 | int i;
558 | IntPtr codebase = module.codeBase;
559 | var section = PointerHelpers.ToStruct(headers,
560 | (uint) (24 + dosHeader.e_lfanew + oldHeaders.FileHeader.SizeOfOptionalHeader));
561 | for (i = 0; i < module.headers.FileHeader.NumberOfSections; i++)
562 | {
563 | IntPtr dest;
564 | if (section.SizeOfRawData == 0)
565 | {
566 | uint size = oldHeaders.OptionalHeader.SectionAlignment;
567 | if (size > 0)
568 | {
569 | dest = new IntPtr((Win32Imports.VirtualAlloc((uint) (codebase + (int) section.VirtualAddress),
570 | size, Win32Constants.MEM_COMMIT,
571 | Win32Constants.PAGE_READWRITE)));
572 |
573 | section.PhysicalAddress = (uint) dest;
574 | var write = new IntPtr(headers.ToInt32() +
575 | (32 + dosHeader.e_lfanew + oldHeaders.FileHeader.SizeOfOptionalHeader) +
576 | (Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER)) * (i)));
577 | Marshal.WriteInt32(write, (int) dest);
578 | var datazz = new byte[size + 1];
579 | Marshal.Copy(datazz, 0, dest, (int) size);
580 | }
581 |
582 | section = PointerHelpers.ToStruct(headers,
583 | (uint) ((24 + dosHeader.e_lfanew + oldHeaders.FileHeader.SizeOfOptionalHeader) +
584 | (Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER)) * (i + 1))));
585 | continue;
586 | }
587 |
588 | dest = new IntPtr((Win32Imports.VirtualAlloc((uint) (codebase + (int) section.VirtualAddress),
589 | section.SizeOfRawData, Win32Constants.MEM_COMMIT,
590 | Win32Constants.PAGE_READWRITE)));
591 | Marshal.Copy(data, (int) section.PointerToRawData, dest, (int) section.SizeOfRawData);
592 | section.PhysicalAddress = (uint) dest;
593 | var write2 = new IntPtr(headers.ToInt32() +
594 | (32 + dosHeader.e_lfanew + oldHeaders.FileHeader.SizeOfOptionalHeader) +
595 | (Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER)) * (i)));
596 | Marshal.WriteInt32(write2, (int) dest);
597 | section = PointerHelpers.ToStruct(headers,
598 | (uint) ((24 + dosHeader.e_lfanew + oldHeaders.FileHeader.SizeOfOptionalHeader) +
599 | (Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER)) * (i + 1))));
600 | }
601 | }
602 | }
603 | }
--------------------------------------------------------------------------------
/DynamicDLLLoader/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Runtime.InteropServices;
4 |
5 | namespace DynamicDLLLoader
6 | {
7 | internal class Program
8 | {
9 | //[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
10 | //public delegate void SomeExportedFunctionInTheDll();
11 |
12 | [DllImport("kernel32.dll", CharSet=CharSet.Auto)]
13 | public static extern IntPtr GetModuleHandle(string lpModuleName);
14 |
15 | static unsafe void Main(string[] args)
16 | {
17 | byte[] dat = File.ReadAllBytes(Directory.GetCurrentDirectory() + "\\mono.dll");
18 |
19 | DynamicDllLoader loader = new DynamicDllLoader();
20 | // LoadLibrary accepts a byte array.
21 | bool loaded = loader.LoadLibrary(dat);
22 | Console.WriteLine("Loaded: " + loaded);
23 |
24 | if (loaded)
25 | {
26 | //....
27 | uint xd = loader.GetProcAddress("mono_trace");
28 | Console.WriteLine("Handle: " + xd); // > 0, means that our dll loaded correctly.
29 | }
30 |
31 | Console.ReadKey();
32 |
33 | //uint addr = loader.GetProcAddress("SomeExportedFunction");
34 |
35 | //SomeExportedFunctionInTheDll invoke =
36 | // (SomeExportedFunctionInTheDll)Marshal.GetDelegateForFunctionPointer((IntPtr)addr, typeof(SomeExportedFunctionInTheDll));
37 | //invoke();
38 | }
39 | }
40 | }
--------------------------------------------------------------------------------
/DynamicDLLLoader/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.InteropServices;
3 |
4 | // General Information about an assembly is controlled through the following
5 | // set of attributes. Change these attribute values to modify the information
6 | // associated with an assembly.
7 | [assembly: AssemblyTitle("DynamicDLLLoader")]
8 | [assembly: AssemblyDescription("")]
9 | [assembly: AssemblyConfiguration("")]
10 | [assembly: AssemblyCompany("")]
11 | [assembly: AssemblyProduct("DynamicDLLLoader")]
12 | [assembly: AssemblyCopyright("Copyright © 2019")]
13 | [assembly: AssemblyTrademark("")]
14 | [assembly: AssemblyCulture("")]
15 |
16 | // Setting ComVisible to false makes the types in this assembly not visible
17 | // to COM components. If you need to access a type in this assembly from
18 | // COM, set the ComVisible attribute to true on that type.
19 | [assembly: ComVisible(false)]
20 |
21 | // The following GUID is for the ID of the typelib if this project is exposed to COM
22 | [assembly: Guid("0D19247E-FE11-4F0D-915D-6CA1921A7542")]
23 |
24 | // Version information for an assembly consists of the following four values:
25 | //
26 | // Major Version
27 | // Minor Version
28 | // Build Number
29 | // Revision
30 | //
31 | // You can specify all the values or you can default the Build and Revision Numbers
32 | // by using the '*' as shown below:
33 | // [assembly: AssemblyVersion("1.0.*")]
34 | [assembly: AssemblyVersion("1.0.0.0")]
35 | [assembly: AssemblyFileVersion("1.0.0.0")]
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # DynamicDllLoader
2 | DynamicDllLoader in C# for **native dlls (C / C++)**
3 |
4 | # Loading a DLL from memory
5 | This project describes a technique how a dynamic link library (DLL) can be loaded from memory without storing it on the hard-disk first.
6 |
7 | # Overview
8 | The default windows API functions to load external libraries into a program (LoadLibrary, LoadLibraryEx) only work with files on the filesystem. It’s therefore "impossible" to load a DLL from memory. (You could do a similar way of managed injection) But sometimes, you need exactly this functionality (e.g. you don’t want to distribute a lot of files or want to make disassembling harder). Common workarounds for these problems are to write the DLL into a temporary file first and import it from there. We could also store the byte array in our program, or in an encrypted temp file. When the program terminates, the temporary file gets deleted.
9 |
10 | # C++ Source
11 | https://www.joachim-bauch.de/tutorials/loading-a-dll-from-memory/
12 |
--------------------------------------------------------------------------------