CodeGuru
Earthweb Search
Forums Wireless Jars Gamelan Developer.com
CodeGuru Navigation
Member Sign In
User ID:
Password:
Remember Me:
Forgot Password?
Not a member?
Click here for more information and to register.

jobs.internet.com

internet.commerce
Partners & Affiliates
GPS
PDA Phones & Cases
Laptops
Server Racks
Build a Server Rack
KVM Switches
Promos and Premiums
Online Education
Promotional Golf
Computer Hardware
Baby Photo Contest
Computer Deals
Phone Cards
Memory Upgrades


RSS Feeds

RSSAll

RSSVC++/C++

RSS.NET/C#

RSSVB

See more EarthWeb Network feeds

Home >> Visual C++ / C++ >> Windows Programming >> Win32 >> Security

Best Practices for Developing a Web Site: Checklists, Tips, Strategies & More. Download Exclusive eBook Now.

Injective Code Inside an Import Table
Rating:

Ashkbiz Danehkar (view profile)
July 13, 2006

Environment:  VC 8.0, NT4, Win2K, WinXP, Win2003, Vista

Go to page: 1  2  3  4  Next

Imagine that you could redirect the thoroughfare of the imported function's entrances into your special routines by manipulating the import table thunks. It could be possible to filter the demands of the importations through your routines. Furthermore, you could settle your appropriate routine by this performance, which is done by the professional Portable Executable (PE) Protectors. Additionally, some sort of rootkits employ this approach to embed its malicious code inside the victim by a Trojan horse.


(continued)

Click Here

Web Devs:
Moonlight as a Game Developer and Win Cool Prizes by Accepting the RIA Run Challenge

Now, your mission--should you choose to accept: Take your shot at gaming stardom if you think you might have what it takes to build a cool RIA game and you could win an Xbox 360 or other fabulous prizes. Hurry! You only have until May 15, 2008 to enter. »

 
Article:
Leveraging Your Flash Development with Silverlight

You're not giving up Flash any time soon (and we don't blame you.) But if you could get your Flash application working in Silverlight, why wouldn't you? We show you the tools and techniques required to have your rockin' Flash application rolled for Silverlight. Learn more here. »

 
Article:
What Does it Take to Build the Best RIA?

With the proliferation of Rich Interactive Application (RIA) platform choices out there, you no longer have to take a one-size-fits-all approach to developing your next RIA application. Knowing the strengths (and weaknesses) of each platform can help you to decide the best RIA for your next application. »

 

In the reverse engineering world, it's described as an API redirection technique. Nevertheless, I am not going to accompany all viewpoints in this area with source code. This article merely represents a brief aspect of this technique by a simple code. I will describe other issues in the absence of the source code; I could not release the code that is related to commercial projects or intended to a malicious motivation. However, I think this article could be used as an introduction into this topic.

1. Intoduction to the Import Table

The portable executable file structure consists of the MS-DOS header, the NT headers, the Sections headers, and the Section images, as you observe in Figure 1. The MS-DOS header is common in all Microsoft executable file formats from the DOS days to the Windows days. The NT headers idea was abstracted form the Executable and Linkable Format (ELF) of the UNIX System. Indeed, the Portable Executable (PE) format is sister of the Linux Executable and Linkable Format (ELF). The PE format headers consist of the "PE" Signature, the Common Object File Format (COFF) header, the Portable Executable Optimal header, and the Section headers.

Figure 1: Portable Executable file format structure

The definition of the NT headers can be found in the <winnt.h> header file of the Virtual C++ included directory. This information can be retrieved very easily by using ImageNtHeader() from DbgHelp.dll. You also can employ the DOS header to fetch the NT headers, so the last position of the DOS header, e_lfanew, represents the offset of the NT headers.

typedef struct _IMAGE_NT_HEADERS {
   DWORD Signature;
   IMAGE_FILE_HEADER FileHeader;
   IMAGE_OPTIONAL_HEADER OptionalHeader;
} IMAGE_NT_HEADERS, *PIMAGE_NT_HEADERS;

In the Portable Executable Optional header, there are some data directories that delineate the relative location and the size of the principal information tables inside the virtual memory of the current process. These tables can hold information about resource, import, export, relocation, debug, thread local storage, and the COM runtime. It is impossible to find a PE executable file without the import table; this table contains the DLL names and the Functions names that are essential when the program requests them by their virtual addresses. The resource table is not found in the Console executable files; nevertheless, it is a vital part of the Windows executable files with a Graphic User Interface (GUI). The export table is necessary when a dynamic link library exports its function outside and also in an OLE Active-X container. The Dot NET virtual machine could not be executed unescorted by the COM+ runtime header. As you discerned, each table has a special commission in the PE format; see Table 1.

Table 1: Data Directories

Data Directories 0 Export Table
1 Import Table
2 Resource Table
3 Exception Table
4 Certificate File
5 Relocation Table
6 Debug Data
7 Architecture Data
8 Global Ptr
9 Thread Local Storage Table
10 Load Config Table
11 Bound Import Table
12 Import Address Table
13 Delay Import Descriptor
14 COM+ Runtime Header
15 Reserved
// <winnt.h>

#define IMAGE_NUMBEROF_DIRECTORY_ENTRIES    16

// Optional header format.

typedef struct _IMAGE_OPTIONAL_HEADER {

   ...

   IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
} IMAGE_OPTIONAL_HEADER32, *PIMAGE_OPTIONAL_HEADER32;


// Directory Entries
#define IMAGE_DIRECTORY_ENTRY_EXPORT     0 // Export Directory
#define IMAGE_DIRECTORY_ENTRY_IMPORT     1 // Import Directory
#define IMAGE_DIRECTORY_ENTRY_RESOURCE   2 // Resource Directory
#define IMAGE_DIRECTORY_ENTRY_BASERELOC  5 // Base Relocation Table
#define IMAGE_DIRECTORY_ENTRY_DEBUG      6 // Debug Directory
#define IMAGE_DIRECTORY_ENTRY_TLS        9 // TLS Directory

You can obtain the position and size of the import table with only two or three lines of code. By knowing the position of the import table, you can move to the next step to retrieve the DLL names and the Function names. It will be discussed in the following section.

PIMAGE_NT_HEADERS pimage_nt_headers = ImageNtHeader(pImageBase);
DWORD it_voffset = pimage_nt_headers->OptionalHeader.
   DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;

PIMAGE_DOS_HEADER pimage_dos_header = PIMAGE_DOS_HEADER(pImageBase);
PIMAGE_NT_HEADERS pimage_nt_headers = (PIMAGE_NT_HEADERS)
   (pImageBase + pimage_dos_header->e_lfanew);
DWORD it_voffset = pimage_nt_headers->OptionalHeader.
   DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;

2. Import Descriptor at a Glance

The import directory entry of the import table leads you to the position of the import table inside the file image. There is a container for each imported DLL, import descriptor, that embraces the address of first thunk and the address of original first thunk, the pointer to the DLL name. The First Thunk refers to the location of the first thunk; the thunks will be initialized by the PE loader of Windows during the running of the program, as shown in Figure 5. The Original First Thunk points to the first storage of the thunks, where the address of the Hint data and the Function Name data for each functions is provided, Figure 4. In that case, the First Original Thunk is not present; the First Thunk refers to where the Hint data and the Function Name data are located, Figure 3.

The import descriptor is represented with IMAGE_IMPORT_DESCRIPTOR structures, as in the following definition:

typedef struct _IMAGE_IMPORT_DESCRIPTOR {
   DWORD   OriginalFirstThunk;
   DWORD   TimeDateStamp;
   DWORD   ForwarderChain;
   DWORD   Name;
   DWORD   FirstThunk;
} IMAGE_IMPORT_DESCRIPTOR, *PIMAGE_IMPORT_DESCRIPTOR;
Member Description
OriginalFirstThunk Points to the first thunk, IMAGE_THUNK_DATA. The thunk holds the address of the Hint and the Function name.
TimeDateStamp Contains the time/data stamp if there is binding. If it is 0, no binding in imported DLL has happened. In newer days, it sets to 0xFFFFFFFF to describe that binding occurred.
ForwarderChain In the old version of binding, it refers to the first forwarder chain of the API. It can be set 0xFFFFFFFF to describe no forwarder.
Name Shows the relative virtual address of DLL name.
FirstThunk Contains the virtual address of the first thunk arrays that is defined by IMAGE_THUNK_DATA. The thunk is initialized by a loader with a function virtual address. In the absence view of the Orignal First Thunk, it points to the first thunk, the thunks of the Hints, and the Function names.
typedef struct _IMAGE_IMPORT_BY_NAME {
   WORD    Hint;
   BYTE    Name[1];
} IMAGE_IMPORT_BY_NAME, *PIMAGE_IMPORT_BY_NAME;

typedef struct _IMAGE_THUNK_DATA {
   union {
      PDWORD                 Function;
      PIMAGE_IMPORT_BY_NAME  AddressOfData;
   } u1;
} IMAGE_THUNK_DATA, *PIMAGE_THUNK_DATA;

Figure 3: Import Table View

Figure 4: Import Table View with Orignal First Thunk

These two import tables (Figures 3 and 4) illustrate the difference between an import table with and without the original first thunk.

Figure 5: Import Table after overwritten by PE loader

You can use Dependency Walker, Figure 6, to observe all the information of the import table. By the way, I have provided another tool, Import Table viewer, Figure 7, with simple and similar operation. I am sure its source will help you understand the main representation that is done by this kind of equipment.

Figure 6: Dependency Walker, Steve P. Miller

Here, you observe a simple source that could be used to display the import DLLs and the import Functions with a console mode program. However, I think my Import Table viewer, Figure 7, has more incentive to follow the topic because of its graphic user interface.

PCHAR       pThunk;
PCHAR       pHintName;
DWORD       dwAPIaddress;
PCHAR       pDllName;
PCHAR       pAPIName;
//----------------------------------------
DWORD dwImportDirectory= RVA2Offset(pImageBase, pimage_nt_headers->
   OptionalHeader.
   DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress);
//----------------------------------------
PIMAGE_IMPORT_DESCRIPTOR pimage_import_descriptor=
   (PIMAGE_IMPORT_DESCRIPTOR)
   (pImageBase+dwImportDirectory);
//----------------------------------------
while(pimage_import_descriptor->Name!=0)
{
   pThunk= pImageBase+pimage_import_descriptor->FirstThunk;
   pHintName= pImageBase;
   if(pimage_import_descriptor->OriginalFirstThunk!=0)
   {
        pHintName+= RVA2Offset(pImageBase,
           pimage_import_descriptor->OriginalFirstThunk);
   }
   else
   {
      pHintName+= RVA2Offset(pImageBase,
         pimage_import_descriptor->FirstThunk);
   }
   pDllName= pImageBase + RVA2Offset(pImageBase,
      pimage_import_descriptor->Name);
   printf(" DLL Name: %s First Thunk: 0x%x", pDllName,
          pimage_import_descriptor->FirstThunk);
   PIMAGE_THUNK_DATA pimage_thunk_data= (PIMAGE_THUNK_DATA) pHintName;
   while(pimage_thunk_data->u1.AddressOfData!=0)
   {
      dwAPIaddress= pimage_thunk_data->u1.AddressOfData;
      if((dwAPIaddress&0x80000000)==0x80000000)
      {
         dwAPIaddress&= 0x7FFFFFFF;
         printf("Proccess: 0x%x", dwAPIaddress);
      }
      else
      {
         pAPIName= pImageBase+RVA2Offset(pImageBase, dwAPIaddress)+2;
         printf("Proccess: %s", pAPIName);
      }
      pThunk+= 4;
      pHintName+= 4;
      pimage_thunk_data++;
   }
   pimage_import_descriptor++;
}


(
Full Size Image)

Figure 7: Import Table viewer

Go to page: 1  2  3  4  Next

Downloads

  • itview.zip -
  • pemaker6.zip -
  • pemaker7.zip -
  • zimport.zip -

    Tools:
    Add www.codeguru.com to your favorites
    Add www.codeguru.com to your browser search box
    IE 7 | Firefox 2.0 | Firefox 1.5.x
    Receive news via our XML/RSS feed

    Flash Demo: Learn how IBM Information Server Blade is easy to manage, highly scalable and efficient.
    Developing Intelligent Communications? Visit the Avaya DevConnect Center on DevX.
    Best Practices for Developing a Web Site. Checklists, Tips & Strategies. Download Exclusive eBook Now.
    Data Sheet: IBM Information Server Blade
    Generate Complete .NET Web Apps in Minutes . Download Iron Speed Designer today.


  • RATE THIS ARTICLE:   Excellent  Very Good  Average  Below Average  Poor  

    (You must be signed in to rank an article. Not a member? Click here to register)

    Latest Comments:
    No Comments Posted.
    Add a Comment:
    Title:
    Comment:
    Pre-Formatted: Check this if you want the text to display with the formatting as typed (good for source code)



    (You must be signed in to comment on an article. Not a member? Click here to register)


    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Win Server ‘08
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES