C # Traversal DLL export function

Source: Internet
Author: User

how does C # traverse a local DLL-derived function written in C + + or e-language? But here I suggest a person who knows nothing about PE

you should probably first fill in this knowledge, I do not know why the PE side of the application in C # How so little, I checked the relevant

C # Knowledge probably only a person wrote about the application of PE or just from the PE information to determine whether the execution of the file is X86 or X64 way

compile, is the C # programmer really poor really can only dot Asp.net/mvc? think about the snow forum those playing inline-asm/

There's a big difference between inline-hook cows and cows, but no matter what language it seems to me, In fact, the focus is on whether people

Heart . Although I'm not sure C # can be embedded in dynamic assembly (AUTO-ASM) but I can guarantee that C # can do inline-hook though it will

less people, but fortunately, at least C # programmers will not be a bunch of slag. But when I wrote the following code, I was too tired to write

The structure part is a bit troublesome and C # is somewhat different from C + + and of course can dynamically offset address done . but that's a bit of a problem, you

It 's not so much fun to work on your address, you might be doing your own half-day results. Found You wrong, that method is used in structural

In the case of a few levels, you can actually raise the grid anyway, people can't read it. Oh. The following code needs to be in a X86 environment

The use of PE information mainly in the code is all 32-bit structure rather than 64-bit PE information structure, so need X86 environment

However, both X86 and X64 methods are equal, but the structure of the two is not the same as symmetry.


PE format, is the Microsoft Win32 Environment Portable executable file such as (EXE/SYS/DLL/VXD/VDM) etc are standard file format

The PE format is derived from the COFF file format on Vax/vms, portable refers to different versions of Windows and different

The format of the PE file on the CPU type is the same, maybe the CPU is different from the binary code, but the various east

The layout of the West is one to the other.

The first byte in the PE file is the MS-DOS information header, which is image_dos_header with the Image_nt_header package

Contains many PE loaders to.

        [STAThread] unsafe static void Main () {IntPtr hfilebase = Win32native._lopen (@ "C:/window            S/system32/atl.dll ", Win32native.of_share_compat); IntPtr hfilemapping = win32native.createfilemapping (Hfilebase, Win32native.null, win32native.page_readonly, 0, 0, NULL            );  IntPtr psdos32pe = Win32native.mapviewoffile (hfilemapping, win32native.file_map_read, 0, 0, win32native.null); E_lfanew 248 Image_dos_header sdos32pe = (image_dos_header) marshal.ptrtostructure (Psdos32pe, typeof (IMA            Ge_dos_header));            IntPtr psnt32pe = (IntPtr) (Sdos32pe.e_lfanew + (long) psdos32pe);            Image_nt_headers snt32pe = (image_nt_headers) marshal.ptrtostructure (Psnt32pe, typeof (Image_nt_headers)); 6E 2E 6F 6D IntPtr psexportdirectory = Win32native.imagervatova (Psnt32pe, Psdos32pe, Snt32pe.            OptionalHeader.ExportTable.VirtualAddress, Win32native.null); Image_export_directory SexportdirecTory = (image_export_directory) marshal.ptrtostructure (Psexportdirectory, typeof (Image_export_directory)); IntPtr ppexportofnames = Win32native.imagervatova (Psnt32pe, Psdos32pe, Sexportdirectory.addressofnames,            Win32native.null); for (UINT i = 0, nnoofexports = sexportdirectory.numberofnames; i < nnoofexports; i++) {INTP TR pstrexportofname = Win32native.imagervatova (Psnt32pe, Psdos32pe, (UINT) Marshal.readint32 (ppexportofnames, (int) (I                * 4)), win32native.null);            Console.WriteLine (Marshal.ptrtostringansi (Pstrexportofname));            } win32native.unmapviewoffile (PSDOS32PE);            Win32native.closehandle (hfilemapping);            Win32native._lclose (hfilebase);        Console.readkey (FALSE); }

Entry Point with entry points

File offset Address

Virtual Address (VA)

Base address Image Base

Relative Virtual address Relative virual Address (RVA)

Formula: RVA (relative virtual address) = VA (virtual address)-Image base (base site)

File offset address and virtual address translation

In the X86 system, the size of each memory page is 4KB

File offset address, offset = RVA (relative virtual address)-δk

File offset address: filename offset = VA (virtual address)-Image base (base site)-δk

For details, please refer to Baidu Encyclopedia, anyway you want to really understand still need to study PE file

Image_nt_headers behind the MS-DOS information header It is the standard Win32 execution file information header, which contains the

Imported function tables, export function tables, resource information tables, CLR runtime headers, IAT, TLS tables, including debug information, etc.

All we have to do now is get the name of the function exported in the DLL, and the DLL belongs to the standard Win32 execution file.

Then we have to get to the image_nt_headers structure, actually need to locate NT structure is very simple,

Because in the provision NT information header behind the DOS information head, namely Image_dos_header. E_lfanew + image_dos_header

So you will see that I have such a sentence in the code IntPtr PSNT32PE = (IntPtr) (Sdos32pe.e_lfanew + (long) psdos32pe);

Image_optional_header Optional Image header is an optional structure, but the image_file_header structure does not meet the PE file

The properties of the requirements definition, so these properties are defined in the optional structure, so file+optional two structures together is a

a complete PE file structure that contains a number of important information fields such as Addressofentrypoint, DataDirectory, Subsystem

But the mention of DataDirectory I would like to say that in C # is not well defined, so in code this field has been defined in another way, DataDirectory

The default is 16 Image_data_directory, so you can see that there are many definitions of that type in the code. They are the table

Information image_directory_entry_export Export table in DataDirectory we now just need to get its information here

We need to use Imagervatova (relative virtual address to virtual address) that's what someone understands, Physical address to virtual address.

Understanding this place was a little tangled, but then relieved. IMagervatova (Nt_h, Dos_h, RVA, rvasection);

Image_data_directory contains two fields, one virtualaddress (RVA) and the other is a size (size) that gets into the structure

RVA but we can't use this address in any way, because the address provided to me doesn't work at all, so we need to put the RVA

Convert to VA using the above mentioned functions, only silently thanks to Microsoft some hehe, when converted will get Image_export_directory

Here I need to remind you that not every datadirectory contains the RVA corresponding structure is export each has its own independent

Explain the structure, don't confuse it, or it will fly high.

We need image_export_directory in Numberofnames (total number of functions) and addressofnames (address of function name)

Two fields, but Addressofnames contains relative virtual address RVA, so we need to do a conversion and return a

effective The char** pointer assumes that the data you provide is valid otherwise returns NULL, since C # you know that char accounts for two bytes, that is char=wchar_t

We look at the data in the pointer is definitely problematic DLL export function names are all ASCII encoded, so for convenience in C # dedicated simply IntPtr convenient through

Marshal to perform a conversion finally just a resource release operation Okay, that's the way it's going to be. The rest of us need to understand more

Using system;using system.runtime.interopservices;//#include "stdafx.h"//#include <imagehlp.h>//#include < windows.h>//#pragma comment (lib, "ImageHlp.lib")

    Static partial class Win32native {[DllImport ("dbghelp", SetLastError = True)]//Pimage_section_header Last        Rvasection public static extern IntPtr Imagervatova (IntPtr ntheaders, IntPtr Base, uint Rva, int lastrvasection); [DllImport ("kernel32", SetLastError = true)] public static extern IntPtr _lopen (string lppathname, int iread        Write); [DllImport ("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern IntPtr Createfilemapp ING (IntPtr hfile, int lpfilemappingattributes, int flprotect, uint dwmaximumsizehigh, uint dwmaximumsizelow, String Lpnam        e); [DllImport ("kernel32.dll", SetLastError = true)] public static extern IntPtr MapViewOfFile (IntPtr hfilemappingobjec        T, int dwdesiredaccess, uint dwfileoffsethigh, uint dwfileoffsetlow, int dwnumberofbytestomap);        [DllImport ("kernel32.dll", SetLastError = true)] public static extern int UnmapViewOfFile (IntPtr hmapfile); [DllImport ("Kernel32.dll ", SetLastError = true)] public static extern int _lclose (INTPTR hfile);    [DllImport ("kernel32.dll", SetLastError = true)] public static extern int CloseHandle (IntPtr hobject);        } static partial class Win32native {public const int NULL = 0;        public const int OF_SHARE_COMPAT = 0;        public const int page_readonly = 2;        public const int file_map_read = 4;    public const int image_directory_entry_export = 0; } [StructLayout (layoutkind.sequential)] public struct Image_dos_header {[MarshalAs (Unmanagedtype.byvalarr       Ay, SizeConst = 2)] [public char[] e_magic;    Magic number public ushort E_CBLP;      Bytes on last page of the file public ushort E_CP;    Pages in file public ushort E_CRLC;     Relocations public ushort E_cparhdr;    Size of header in paragraphs public ushort E_minalloc;   Minimum Extra paragraphs needed public ushort E_maxalloc; Maximum Extra paragraphs needed public ushort E_ss;      Initial (relative) SS value public ushort e_sp;    Initial SP value public ushort e_csum;      Checksum public ushort E_ip;      Initial IP value public ushort E_cs;      Initial (relative) CS value public ushort E_LFARLC;    File Address of Relocation table public ushort E_ovno;    Overlay number [MarshalAs (UnmanagedType.ByValArray, SizeConst = 4)] public ushort[] e_res1;       Reserved words public ushort e_oemid;     OEM identifier (for e_oeminfo) public ushort E_oeminfo; OEM information;    E_oemid specific [MarshalAs (UnmanagedType.ByValArray, SizeConst = ten)] public ushort[] e_res2;      Reserved words public int e_lfanew;        File address of new EXE header private string _e_magic {get {return new string (e_magic);}  } public bool IsValid {          get {return _e_magic = = "MZ";}        }} [StructLayout (layoutkind.explicit)] public struct Image_optional_headers {[FieldOffset (0)]        Public Magictype Magic;        [FieldOffset (2)] public byte majorlinkerversion;        [FieldOffset (3)] public byte minorlinkerversion;        [FieldOffset (4)] public uint Sizeofcode;        [FieldOffset (8)] public uint sizeofinitializeddata;        [FieldOffset] public uint sizeofuninitializeddata;        [FieldOffset (+)] public uint addressofentrypoint;        [FieldOffset] public uint Baseofcode;        PE32 contains this additional field [FieldOffset (in)] public uint baseofdata;        [FieldOffset] public uint ImageBase;        [FieldOffset (+)] public uint sectionalignment;        [FieldOffset] public uint filealignment;        [FieldOffset (+)] public ushort majoroperatingsystemversion; [FieldoFfset] public ushort minoroperatingsystemversion;        [FieldOffset] public ushort majorimageversion;        [FieldOffset] public ushort minorimageversion;        [FieldOffset] public ushort majorsubsystemversion;        [FieldOffset] public ushort minorsubsystemversion;        [FieldOffset] public uint win32versionvalue;        [FieldOffset ()] public uint sizeofimage;        [FieldOffset] public uint sizeofheaders;        [FieldOffset] public uint CheckSum;        [FieldOffset ()] public subsystemtype Subsystem;        [FieldOffset] public dllcharacteristicstype dllcharacteristics;        [FieldOffset] public uint Sizeofstackreserve;        [FieldOffset] public uint sizeofstackcommit;        [FieldOffset] public uint Sizeofheapreserve;        [FieldOffset] public uint sizeofheapcommit; [FieldOffset ()] public uint loaderflags;        [FieldOffset] public uint numberofrvaandsizes;        [FieldOffset] public image_data_directory exporttable;        [FieldOffset (104)] public image_data_directory importtable;        [FieldOffset ()] public image_data_directory resourcetable;        [FieldOffset] public image_data_directory exceptiontable;        [FieldOffset] public image_data_directory certificatetable;        [FieldOffset (136)] public image_data_directory baserelocationtable;        [FieldOffset (144)] public image_data_directory Debug;        [FieldOffset] public image_data_directory Architecture;        [FieldOffset] public image_data_directory globalptr;        [FieldOffset (168)] public image_data_directory tlstable;        [FieldOffset (176)] public image_data_directory loadconfigtable;        [FieldOffset (184)] public image_data_directory boundimport; [FieldOffset(192)] public image_data_directory IAT;        [FieldOffset] public image_data_directory delayimportdescriptor;        [FieldOffset (208)] public image_data_directory clrruntimeheader;    [FieldOffset (216)] public image_data_directory Reserved;        } [StructLayout (layoutkind.sequential)] public struct Image_file_header {public ushort machine;        public ushort Numberofsections;        public UINT TimeDateStamp;        public UINT pointertosymboltable;        public UINT Numberofsymbols;        public ushort Sizeofoptionalheader;    public ushort characteristics; } public enum Machinetype:ushort {Native = 0, I386 = 0x014c, Itanium = 0x0200, x64 = 0x8664} public enum Magictype:ushort {image_nt_optional_hdr32_magic = 0x10b, Image_nt_optional_ Hdr64_magic = 0x20b} public enum Subsystemtype:ushort {image_subsystem_unknown = 0, Image_subsy STEm_native = 1, Image_subsystem_windows_gui = 2, Image_subsystem_windows_cui = 3, Image_subsystem_posix _cui = 7, Image_subsystem_windows_ce_gui = 9, image_subsystem_efi_application = ten, image_subsystem_e Fi_boot_service_driver = one, Image_subsystem_efi_runtime_driver = one, Image_subsystem_efi_rom = one, I Mage_subsystem_xbox = +} public enum Dllcharacteristicstype:ushort {res_0 = 0x0001, res_1 = 0x 0002, res_2 = 0x0004, Res_3 = 0x0008, image_dll_characteristics_dynamic_base = 0x0040, image_d Ll_characteristics_force_integrity = 0x0080, Image_dll_characteristics_nx_compat = 0x0100, image_dllcharacte Ristics_no_isolation = 0x0200, Image_dllcharacteristics_no_seh = 0x0400, Image_dllcharacteristics_no_bind = 0x0800, Res_4 = 0x1000, Image_dllcharacteristics_wdm_driver = 0x2000, image_dllcharacteristics_termin Al_server_aware = 0x8000    } [StructLayout (layoutkind.sequential)] public struct Image_data_directory {public uint Virtualaddres        S    public UINT Size; } [StructLayout (layoutkind.sequential)] public struct Image_export_directory {public UINT characteristics        ;        public UINT TimeDateStamp;        public ushort MajorVersion;        public ushort MinorVersion;        public UINT Name;        public UINT Base;        public UINT Numberoffunctions;        public UINT Numberofnames;     public UINT Addressoffunctions;     RVA from base of image public uint addressofnames;  RVA from base of image public uint addressofnameordinals; RVA from base of Image} [StructLayout (layoutkind.explicit)] public struct Image_nt_headers {[Field        Offset (0)] [MarshalAs (UnmanagedType.ByValArray, SizeConst = 4)] public char[] Signature;        [FieldOffset (4)] public image_file_header fileheader;   [FieldOffset (24)]     Public Image_optional_headers Optionalheader;        private string _signature {get {return new string (Signature);} } public bool IsValid {get {return _signature = = "Pe\0\0" && (optionalheader.magic = = M Agictype.image_nt_optional_hdr32_magic | | Optionalheader.magic = = magictype.image_nt_optional_hdr64_magic); }        }    }


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

C # Traversal DLL export function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.