Post Pacific  

Go Back   Post Pacific > Восстановленный архив > Темы без сохранившегося раздела

Notices

 
 
Thread Tools Search this Thread Display Modes
Old 18.05.2005, 15:54   #1
Riane
Архивный участник
 
Join Date: Apr 2005
Posts: 196
Default @developers

i was thinking of a possible way to extend the l2server to do the new c2 features which arent included in C1, and what came into my mind was some kind of C2 emulator/C1 Server hybrid.
the server which has some stuff already added, but only whats stable, runs as normal.
but the C2 emu app runs in the background proxying the server's connection, and if it detects a packet thats not supported by the old server, it blocks it and acts as the server for it.
e.g. when s/o sends the recipe book packet, the app blocks it from reaching the server and sends the recipe list to the client, when using a recipe, it adds that recipe to the (new) recipebook table in sql, etc...
this will be pretty resource taking i guess, but it is a way to fully implement C2 and C3.
Riane is offline  
Old 18.05.2005, 17:39   #2
Livid
Архивный участник
 
Join Date: Apr 2005
Posts: 314
Default

Im sorry, but don't u think it would be easier to rewrite server? Or you are kinda nervous abt asm? Well, actually there's some reason to this erm... idea. But I think it's not worth trying.
Livid is offline  
Old 18.05.2005, 17:53   #3
Riane
Архивный участник
 
Join Date: Apr 2005
Posts: 196
Default

umm you know l2j?
they are trying to rewrite the server since ob and theirs still suck
this is just easier and most likely still not as resource taking as l2j.
afaik you could never run a 3k+ players server with l2j
Riane is offline  
Old 18.05.2005, 17:57   #4
Livid
Архивный участник
 
Join Date: Apr 2005
Posts: 314
Default

I meant C1 server modding... erm... as we do now. sorry for a little... erm... well, you understand what I mean.
Yes, I know l2j. It's nice project... but as to me, they will finish c2 by the time c10 will be out.
Livid is offline  
Old 18.05.2005, 18:15   #5
Riane
Архивный участник
 
Join Date: Apr 2005
Posts: 196
Default

ah you wanted to add code to the server.
the problem is its already compiled, so its VERY hard to change stuff, even much harder to add complete new code
see how long it took for the ride?
it would be a thing of minutes with the off/emu hybrid, IMO
Riane is offline  
Old 18.05.2005, 18:25   #6
Livid
Архивный участник
 
Join Date: Apr 2005
Posts: 314
Default

Not actually minutes... We would need to analyze packet structure for some kinda long time. Well, as I told already, there's some reason in this idea. Ok, may be we could try. Anyone else?
Livid is offline  
Old 18.05.2005, 19:30   #7
Riane
Архивный участник
 
Join Date: Apr 2005
Posts: 196
Default

packet structure is the easiest thing in this whole stuff
i guess the hardest thing would be the communication between the emu and the server, but i guess l2atl stuff will help there
Riane is offline  
Old 18.05.2005, 21:32   #8
theRAGE
Архивный участник
 
Join Date: Feb 2005
Posts: 82
Default

Quote:
Originally Posted by Riane
umm you know l2j?
they are trying to rewrite the server since ob and theirs still suck
this is just easier and most likely still not as resource taking as l2j.
afaik you could never run a 3k+ players server with l2j
And when was the last time you checked out L2J? In my opinion, L2J has come a long way in the last few months (not official releases but the L2JRU releases, etc.). The reason why the project has slowed down officially, is because no one is really helping the main project and want to form their own release teams and such. Another reason is that L2J refuse to use data from the official leaked server files since they are illegal.

I myself, hate Java... and would never consider joining their dev team. But I wouldn't mind this group putting their energy towards a C++ and Oracle DB server, rather then spending months trying to mod a memory-inefficient, non-cross-platform, illegal server program.
theRAGE is offline  
Old 18.05.2005, 22:03   #9
Riane
Архивный участник
 
Join Date: Apr 2005
Posts: 196
Default

Quote:
rather then spending months trying to mod a memory-inefficient, non-cross-platform, illegal server program.
correct me if im wrong, but umm thats exactly what you do here, isnt it?!
Riane is offline  
Old 18.05.2005, 23:18   #10
theRAGE
Архивный участник
 
Join Date: Feb 2005
Posts: 82
Default

Quote:
Originally Posted by Riane
Quote:
rather then spending months trying to mod a memory-inefficient, non-cross-platform, illegal server program.
correct me if im wrong, but umm thats exactly what you do here, isnt it?!
...
Yes, that is exactly what I'm saying... learn some friggin english before trying to correct me.
theRAGE is offline  
Old 19.05.2005, 03:43   #11
Livid
Архивный участник
 
Join Date: Apr 2005
Posts: 314
Default

Quote:
Originally Posted by Riane
packet structure is the easiest thing in this whole stuff
i guess the hardest thing would be the communication between the emu and the server, but i guess l2atl stuff will help there
That's not a hard thing. We just ned do communicate not with entire server, but only with cacheD (correct me if im wrong) - so, again, week sniffing, then just add protocol to "proxy".
The problem is that you will need to write handler for almost every client request. That's a pain in the ass.
Livid is offline  
Old 19.05.2005, 04:29   #12
Digital
Архивный участник
 
Join Date: Nov 2004
Posts: 1,405
Default

not exactly...
we can pick up packets that we want instead of tracking every single packet sent to the server...
the hard part here would be how to stop the server from sending error/invalid data packet back (at the same time when our hook program does send something back as well)

i think it's more likely to hook into l2server, but it's gonna be difficult.
but if we could do this.... it's gonna be seriously worth it.
since it'll mean we could do anything from then on... just like what l2j could do as well
Digital is offline  
Old 19.05.2005, 12:54   #13
Riane
Архивный участник
 
Join Date: Apr 2005
Posts: 196
Default

@rage stfu when it comes to languages, i bet you can just speak one
english isnt my first language and im only 17, so IMHO my english is good

@digital
such a hook was in my mind (have not much experience with that stuff, just using aimbots etc lol)
for the error part, if its possible to block those "filtered" packets from reching the server.exe, it wont create errors, thats my idea, do all the traffic over that hook or whatever, and if a certain packet is found->no redirecting but acting as the server itself
Riane is offline  
Old 19.05.2005, 17:42   #14
theRAGE
Архивный участник
 
Join Date: Feb 2005
Posts: 82
Default

Quote:
Originally Posted by Riane
@rage stfu when it comes to languages, i bet you can just speak one
english isnt my first language and im only 17, so IMHO my english is good
I'm Canadian, bitch. Meaning I'm forced to learn both English and French. And whats that? I'm only 16... so IMHO I pwn you :P

Lighten up dude... I never knew Germans were so hostile.
theRAGE is offline  
Old 19.05.2005, 18:19   #15
-sky-
Архивный участник
 
Join Date: Apr 2005
Posts: 15
Default

Quote:
Originally Posted by Digital
not exactly...
we can pick up packets that we want instead of tracking every single packet sent to the server...
the hard part here would be how to stop the server from sending error/invalid data packet back (at the same time when our hook program does send something back as well)

i think it's more likely to hook into l2server, but it's gonna be difficult.
but if we could do this.... it's gonna be seriously worth it.
since it'll mean we could do anything from then on... just like what l2j could do as well
nope, you can't simply pick up or delete single packet, because the second part of encription/decription key (4 of 8 bytes) depends on the size of last packet accepted or sent... if you change size or delete packet you must reencode all packets from/to server in game session....
-sky- is offline  
Old 20.05.2005, 02:41   #16
Digital
Архивный участник
 
Join Date: Nov 2004
Posts: 1,405
Default

@-sky-
it should be something like this.
things unknown direct to - server
things known direct to - hook program

so what we actually do here is to identify the packets we want to intercept
just like routing for networking
if ip is on network forward to it
if not forward out from gateway, etc

is there anyone here who could give this hook program a shot?
cuz frankly speaking i aint got the skills to do it :|
Digital is offline  
Old 20.05.2005, 14:56   #17
Riane
Архивный участник
 
Join Date: Apr 2005
Posts: 196
Default

@rage i speak 3 languages, furthermore, english i guess is your mother language
and dont take one german as every german, im special

for the hook:
cant do it too lol thats why i posted it
anyone?
Riane is offline  
Old 20.05.2005, 15:15   #18
iamrend
Архивный участник
 
Join Date: May 2005
Posts: 315
Default

That i need for enter in developers forums? im developing a c2 server and need to fix some bugs
iamrend is offline  
Old 22.05.2005, 00:44   #19
badjoe
Архивный участник
 
Join Date: Feb 2005
Posts: 72
Default

started working on some sort of proxy server that would modify on the fly some packets that changed from C1 to C2 (like abnormal visual effects) but I had to pause it no time right now
badjoe is offline  
Old 22.05.2005, 02:38   #20
Digital
Архивный участник
 
Join Date: Nov 2004
Posts: 1,405
Default

hmm.. guess nobody is working on it then i guess :|
and the evil empire m$ might just solve all our problems instead
http://www.microsoft.com/whdc/device/network/WFP.mspx
Digital is offline  
Old 22.05.2005, 13:33   #21
Riane
Архивный участник
 
Join Date: Apr 2005
Posts: 196
Default

sounds good
hehe new problem: how to get a hand on it^^
Riane is offline  
Old 22.05.2005, 15:16   #22
toolpunk
Архивный участник
 
Join Date: May 2005
Posts: 2,033
Default

have u ever heard of torrents^^
but thats illegal so dont do that
u BAD BAD BOY
i know that u know torrents i know everything here must b illegal server files mssql which cost only more than 1000$ and so on
and i even know u will dl it via torrent anyway i cant stop u but i warned u...
toolpunk is offline  
Old 23.05.2005, 13:09   #23
Digital
Архивный участник
 
Join Date: Nov 2004
Posts: 1,405
Default

API Hook SDK is a Software Development Kit for hooking Windows 32bit API functions,it will call your own function instead of Windows call some API. API Hook SDK also can hookthe functions in 3rd Appliction's DLL.

Table of contents

Features
File List
Usage
HookFunc project
HookSetup.dll
Compile and run

Features:

1. Your own functions have the same form as the API functions you need to hook, it is easy to use.
2. Hooks process in real time, that means it will install hook just when the process has created.
3. Takes very little system resource and nearly no CPU time consumed.

File List:

HookDemo.exe: Call HookSetup.dll to Setup API Hook
HookSetup.dll: Setup API Hook DLL
APIHookxp.dll: Win32 API Hook DLL for WINNT/2000/XP
APIHook9x.dll: Win32 API Hook DLL for WIN9X/WINME
HookFunc.dll: Your own DLL include functions that will be called when hook occurred

APIHook Directory: Source code of Win32 API Hook DLL
ADFilter Directory: Source code of Internet Advertising Filter example
DESCrypt Directory: Source code of DES Cryptological Library
FileDelphi Directory: Source code of File access hook function Delphi example
FileHook Directory: Source code of File access hook function example
HookDemo Directory: Source code of HookDemo program
HookSetup Directory: Source code of API Hook setup DLL
MsgHook Directory: Source code of system message hook function example
NetCrypt Directory: Source code of network transmission crypto function example
ProcHide Directory: Source code of hide process from taskmanager function example
RegHook Directory: Source code of registry hook function example
SocketDelphi Directory: Source code of socket hook function Delphi example
SocketHook Directory: Source code of socket hook function example

Usage:

Developer only need write the function related with the functions you want to hook, compiled HookFunc.dll, and call install and uninstall function at HookSetup.dll, it will implement the hook.

HookFunc project:
Create DLL project file - HookFunc
If the project name is not HookFunc, modify the output file name to HookFunc.dll
Modify HookFunc.cpp and HookFunc.def
Compile and link the project, it will output file HookFunc.dll
HookFunc project contain something as below:

1) HookFunc.h, there is only CAPIINFO structure definite in this file:

#ifndef _HookFunc_h_
#define _HookFunc_h_

typedef struct
{
char *module_name;
char *func_name;
char *c_func_name;
}CAPIINFO;

module_name is the name of a DLL or other module file name that will be hooked, for example : kernel32.dll

func_name is the function name and parameters of user’s DLL that will be hooked, like C style format ,for examples:
connect(SOCKET, struct sockaddr *, INT)

c_func_name is your own function that called as the related function hooked, for examples:
cConnect(SOCKET s, struct sockaddr *name, int namelen).

2) Define CAPIINFO c_api_info[] and fill it, must be NULL in the end, It is the hook function information, for examples:

CAPIINFO c_api_info[] = {
{"WSOCK32.DLL", "socket(INT, INT, INT)", "cSocket"},
{"WSOCK32.DLL", "connect(SOCKET, struct sockaddr *, INT)", "cConnect"},
{"WSOCK32.DLL", "recv(INT, char *, INT, INT)", "cRecv"},
{"WSOCK32.DLL", "send(INT, char *, INT, INT)", "cSend"},
{"ADVAPI32.DLL", "RegOpenKeyA(HKEY, LPCSTR, PHKEY)", "cRegOpenKeyA"},
{NULL,NULL,NULL} }; //must contain this

3) Must be define function GetCAPIINFO:

CAPIINFO *GetCAPIINFO()
{ return &c_api_info[0]; }

4) Coding with user function, for example:

DWORD _cdecl cFuncName(type1 param1, type2, param2, …)

The function must be defined with WINAPI (in Delphi it is stdcall), the function definite must be as same as original function, for example:

int WINAPI cConnect(SOCKET s, struct sockaddr *name, int namelen)
{
struct sockaddr_in *paddr =(struct sockaddr_in *)name;
char *ip =inet_ntoa(paddr->sin_addr);
int port =ntohs(paddr->sin_port);
int ret =connect(s, name, namelen);
int err=WSAGetLastError();
WriteLog("connect: ip=%s, port=%d, ret=%d\n", ip, port, ret); // check filter
WSASetLastError(err);
return ret; }

in the example, we recovery error code, because when we handle with our own procedure, the error code will change, and the original process could be do next according to the error code.even cConnect not call original connect, we must use WSASetLastError or SetLastError to set error code when cConnect return. Other functions should do as the same.

By the way, in win9x, it is best to call the original API functions in HookFunc for HookFunc will call the original dll module, otherwise before call HookFunc, first use LoadLibrary() to load original dll file in apihook application, hook could be failed if not do like this sometimes.

5) HookFunc.def contains GetCAPIINFO and users functions exports, for example:

LIBRARY HookFunc

EXPORTS
GetCAPIINFO @1
cRegOpenKeyA @2
cRegOpenKeyW @3
cRegQueryValueA @4
cRegQueryValueW @5
cRegQueryValueExA @6
cRegQueryValueExW @7

HookSetup.dll
HookSetup.dll contain these functions (refer to HookSetup.h):

1) int WINAPI InitAPIHook();
2) int WINAPI HookAllProcesses();
3) int WINAPI UnhookAllProcesses();
4) int WINAPI NTHookProcess(DWORD process_id);
5) int WINAPI NTUnhookProcess(DWORD process_id);
6) int WINAPI NTHookProcess2(char *mod_name);
7) int WINAPI NTUnhookProcess2(char *mod_name).
Compile and run
Build the APIHook,HookSetup and HookFunc projects, put APIHookxp.dll (or APIHook9x.dll),HookSetup.dll,HookFunc.dll and your application which use the hook functions (e.g. Hookdemo.exe) to the same directory,then run your application, that's done.

Validtec Software, Inc.
http://www.validtec.com
January 28, 2004
Digital is offline  
Old 23.05.2005, 13:12   #24
Digital
Архивный участник
 
Join Date: Nov 2004
Posts: 1,405
Default

Matt Pietrek does advanced research for the NuMega Labs of Compuware Corporation, and is the author of several books. His Web site, at http://www.wheaty.net/, has a FAQ page and information on previous columns and articles.

In the December 1998 issue of MSJ, Jeffrey Richter and I wrote dueling columns on the DelayLoad feature of the Microsoft® Visual C++® 6.0 linker. The fact that both Jeff and I jumped on this topic is testimony to how cool this feature is. Unfortunately, I still find people who don't know anything about DelayLoad or they think it's some feature that's available only in the latest version of Windows NT®.
For starters, let me scream from the highest rooftop that DelayLoad is not an operating system feature. It works on any Win32®-based system. With that off my chest, I'll demonstrate this month's utility, DelayLoadProfile, which makes it almost trivial to determine whether your program can benefit from DelayLoad. As I'll show, even some of Microsoft's own programs can benefit from it.

A Quick Review
If you're wondering "What's this thing Matt's gone off the deep end over?" a quick recap of DelayLoad is in order. Here's how it works. Normally, when calling an imported function in a DLL, the linker adds information about the imported DLL and function to your executable. Collectively, the information for all the imported functions is known as the imports section.
The Win32 loader scans through the imports section at load time and loads each DLL. For each DLL loaded, the loader iterates through all the imported functions and locates their addresses in the imported DLL. These addresses are written back to the imports section in a location known as the Import Address Table (IAT). A simple way to think of an IAT is as an array of function pointers. When calling an imported function, the call uses one of the function pointers from the IAT.
How does the picture change with DelayLoad? When you specify DelayLoad for a DLL, the linker doesn't emit the usual data it would put in the imports section. Instead, it generates a small stub for each DelayLoad imported function. This stub points to the imported DLL and function name. Upon calling an imported function for the first time, the stub calls LoadLibrary to load the DLL. Next, it calls GetProcAddress to get the address of the called function. Finally, the stub overwrites part of itself so that subsequent calls to the function go directly to the target code.
What I've just described is a slight simplification. In reality, the stub is a small bit of code that calls a routine statically linked into your executable. This routine resides in DELAYIMP.LIB, which must be included in the list of libraries that the linker uses. Also, the stubs and DELAYIMP.LIB code are smart enough to call LoadLibrary only the first time a function in the DLL is used. Subsequent calls to other functions in the same DelayLoad imported DLL don't call LoadLibrary.
All things considered, DelayLoad doesn't add much time or space overhead compared to importing the DLL the usual way. Calling LoadLibrary is only slightly less efficient than letting the Win32 loader load the DLL. Likewise, calling GetProcAddress once for each DelayLoad imported function is only slightly slower than having the Win32 loader locate the imported functions at startup.
However, the benefits of DelayLoad can easily make up for these small speed penalties. For starters, if you never call a function in a DelayLoad imported DLL, the DLL isn't loaded in the first place. This comes in handy more often than you may think. Consider the situation in which you have printing code in your program. If the user doesn't print something during a program session, you've loaded WINSPOOL.DRV for no reason. In this case, using DelayLoad is actually faster since you never loaded and initialized WINSPOOL.DRV.
Another benefit of using DelayLoad is that you avoid calling APIs that are not available on one of your target platforms. For instance, say you want to call AnimateWindow, which is supported in Windows® 98 and Windows 2000, but not Windows 95 or Windows NT 4.0. If you were to call AnimateWindow the usual way, your code wouldn't load on the earlier platforms. However, with DelayLoad you can make a runtime check of which operating system you're on and only call AnimateWindow if it's supported. There's no need for you to muck up your code with calls to LoadLibrary and GetProcAddress.
Using DelayLoad is incredibly easy. Once you know which DLLs you want to use DelayLoad with, simply add /DELAYLOADLLNAME, where DLLNAME is the name of the DLL. You'll also need to add DELAYIMP.LIB to the linker's library list, and you'll still need the original import library, for example, SHELL32.LIB. Putting everything together, to DelayLoad against SHELL32.DLL your linker line would need the following:

SHELL32.LIB /DELAYLOAD:SHELL32.DLL DELAYIMP.LIB


Unfortunately, the Visual Studio® 6.0 IDE doesn't have an easy way for you to specify DelayLoading for DLLs. In Visual Studio 6.0, you'll have to add the /DELAYLOAD:XXX command-line fragment manually to the Project Settings | Link | Project Options edit field.

When to Use DelayLoad
When you have a small project, it's easy to come up with a list of DLLs that are good DelayLoad candidates. However, because projects may grow and can involve many developers, it's just as easy to lose track of who uses which DLL. In the past, I've relied on gut instinct and Depends.EXE from the Platform SDK. A DLL from which only a few functions are imported is a good place to start.
However, I wanted a way to automate and simplify the process. Thus was born the DelayLoadProfile program. DelayLoadProfile is a tool that runs your EXE and monitors the DLLs and functions that your EXE calls. After your program terminates, DelayLoadProfile spits out a summary of which DLLs were used and how many calls were made to each DLL. A DLL that's imported, but which had no calls made to it, is a good candidate for DelayLoad importing.
Let me emphasize one point before continuing: DelayLoadProfile works only against your EXE. While it could be extended to recurse into all of your imported DLLs and their dependencies, that would significantly complicate its code. As I'll explain later, DelayLoadProfile just gives you hints about which DLLs you might consider using /DELAYLOAD on. You still have to use that neuron-based processing unit between your ears to make sure it makes sense to do so.


DelayLoadProfile: The Big Picture
The concept behind DelayLoadProfile is simple. Redirecting the function pointers in the EXE's IAT to point to a stub is all that's needed. The stub simply notes that the imported function has been called, then jumps to the address that the Win32 loader originally stored in the IAT. However, the devil is in the details.
First, you must decide where the code will run that locates and modifies the EXE's IAT entries to point to the stubs. Doing the work out-of-process in some sort of control program is one option. This avoids the work involved in getting your code into the target EXE's process. The downside is that it's more work to traverse all the data structures necessary to locate and patch the IAT entries, as well as gather the results later. I'd be swimming in ReadProcessMemory calls.
The other approach is to do the hard work in the same process space as the target EXE. This makes it almost trivial to march through the data structures, build stubs, redirect the IAT entries, and summarize the results at the end. However, doing the work in-process requires that some of the DelayLoadProfile code be loaded into the target EXE's process as it runs. This is the path I took.
Having committed to running my code in-process with the target, the next problem was figuring out how to get my code into the target process. One choice would have been to ask the user to link with the DelayLoadProfile code. Knowing it would require some effort by the target audience, I discarded this option. If a DelayLoadProfile user needed to modify their source, project, or makefile, many would pass. I needed to make DelayLoadProfile a complete no-brainer.
At this point, I had boxed myself into some sort of loader program that would run the target EXE and inject my DelayLoadProfile DLL into it. One technique for DLL injection is to use CreateRemoteThread to start a thread in the target process that calls LoadLibrary on your DLL. I discarded this approach because CreateRemoteThread isn't available on Windows 9x, which I wanted to support.
Longtime MSJ readers may remember a program I wrote more than five years ago called APISPY32. It loads a process and injects a DLL into it for the purposes of logging API calls. That sounds similar to what I needed DelayLoadProfile to do. Alas, when I ran APISPY32 on Windows 2000, it failed to load the DLL. A little digging revealed the source of the problem, and I decided it was time to revamp this code for a whole new generation of programmers.


Into the Trenches
To review quickly, DelayLoadProfile is a two-part system. A loader process runs your program. Early on in your program, the loader process injects a DLL into your program's address space. This DLL scans through your EXE's IAT and redirects the imported functions to point to stubs that the DLL creates. When your program shuts down, the injected DLL scans through the stubs it has created and summarizes how many calls were made to each imported DLL. If you've ever used the APIMON utility from the Platform SDK, you'll recognize the similarities.
The DLL that does all the work of monitoring a program's use of imports is called DelayLoadProfileDLL (see Figure 1). DelayLoadProfileDLL uses the DLL_PROCESS_ATTACH and DLL_PROCESS_DETACH notifications sent to its DllMain procedure to initiate the two primary phases of the DLL's work.
When its DllMain gets the DLL_PROCESS_ATTACH notification, DelayLoadProfileDLL calls PrepareToProfile. Inside PrepareToProfile, the code locates the target EXE's IAT. For each imported DLL it finds, the code determines if it's a DLL that's safe for IAT redirection. It does this by calling the IsModuleOKToHook function. Most of the time, it's OK to redirect the IAT, so PrepareToProfile invokes the RedirectIAT function.
RedirectIAT is where things get dirty, and it really helps if you understand the import-related data structures in WINNT.H. First, the function locates the IAT and the associated Import Names Table. The code then counts how many IAT entries there are by scanning through the IAT, looking for a NULL pointer. With this count, an array of DLPD_IAT_STUB stubs is created, with one stub for each IAT entry.
Finally, it's time for meatball surgery. The code makes yet another pass through the IAT. This time it grabs the address in each IAT entry, stuffs it into a JMP instruction in the stub, and redirects the IAT entry to point to the stub. As the code advances through each subsequent IAT entry, it also advances to the next DLPD_IAT_STUB stub in the allocated array. I'll explain DLPD_IAT_STUB stubs a little later in this column.
Two aspects of redirecting the IAT entries to the allocated stubs are worth mentioning. First, the IAT is often placed in a read-only section of the EXE. Ordinarily, an attempt to modify such an IAT pointer would result in an access violation. Luckily, the VirtualProtect API comes to the rescue and enables you to modify the attributes of a target address, in this case, the IAT. Read-write is the attribute you're looking to modify. When it's finished, the code restores the original memory protection attributes.
The other tricky part of redirecting the IAT occurs when you encounter a data import. Although programmers don't frequently do so, it's relatively easy to import data in addition to code. The Visual C++ runtime library DLL (MSVCRT.DLL) has data exports. Redirecting an IAT entry that refers to data in an imported DLL is almost certainly a recipe for problems.
So how do you determine whether an import is a normal code import or a data import? A commercial product could implement a sophisticated algorithm to determine the import type of an IAT entry. However, I took a shortcut and used IsBadWritePtr. If the IAT points to memory that's writeable, it's probably pointing to data. Likewise, if it points to read-only memory, odds are that it's pointing to code. Is this a perfect test? No, but it's good enough for DelayLoadProfile's needs.
Now let's take a look at the stubs. The DLPD_IAT_STUB structure in DelayLoadProfileDLL.H contains the layout, which is a mixture of code and data. Simplifying this structure, a DLPD_IAT_STUB stub looks like this:

CALL DelayLoadProfileDLL_UpdateCount
JMP XXXXXXXX // original IAT address
DWORD count
DWORD pszNameOrOrdinal


When the EXE calls one of the redirected functions, control goes to the CALL instruction in the stub. The DelayLoadProfileDLL_UpdateCount routine in DelayLoadProfileDLL.CPP simply increments the value of the count field of the stub. After that CALL returns, the JMP instruction transfers control to the original address that was stored in the IAT before I bashed it. Figure 2 shows the big picture after the IAT has been redirected to the stubs.
Assembler junkies might be wondering how the DelayLoadProfileDLL_UpdateCount function knows where the stub's count field is in memory. A quick look at the code shows that DelayLoadProfileDLL_UpdateCount finds the return address pushed on the stack by the CALL instruction. The return address points to the JMP XXXXXXXX instruction following the call. Since the CALL instruction is always five bytes, some pointer arithmetic yields the stub's starting address and easy access to the stub's count field.
I had one problem using the DelayLoadProfileDLL_UpdateCount code that's worth mentioning. Originally, the function didn't have the PUSHAD and POPAD instructions to save and restore all of the regular CPU registers. The code worked fine on many programs, but just blew up on others. Finally, I narrowed it down to programs that imported __CxxFrameHandler and _EH_prolog from MSVCRT.DLL. Both of these APIs expect the EAX register to be set to a given value, and DelayLoadProfileDLL_UpdateCount was trashing EAX.
Since the trashed EAX was the problem, I added PUSHAD and POPAD. Alas, the problem remained. In frustration, I examined the compiler-generated code, and then smacked my forehead. Normally when generating code for a debug build, the Visual C++ 6.0 compiler inserts code in the function prolog to set all local variables to the value 0xCC. This code was trashing EAX before my PUSHAD got a chance to execute. To get around this, I had to remove the /GZ option from the debug build settings for DelayLoadProfileDLL.

Reporting Results
As your process shuts down, the system sends the DLL_ PROCESS_DETACH notification to all loaded DLLs. DelayLoadProfileDLL uses this opportunity to harvest the information collected during the run. In a nutshell, this means scanning through all the stub arrays, counting the number of calls that were made through the stubs, and reporting what it finds.
During the setup phase when DelayLoadProfileDLL was redirecting the IATs, it stashed away the address of the EXE's IAT into a global variable (g_pFirstImportDesc). At shutdown time, ReportProfileResults uses this pointer to walk through the imports section again. For each imported DLL, it retrieves the address of the DLL's first IAT entry. If this is an IAT that I've redirected, the first pointer in the IAT should point to the first of the DLPD_IAT_STUB stubs allocated for that DLL. Of course, the code does some sanity checking to ensure that this is the case. If something doesn't look right, DelayLoadProfileDLL ignores that particular imported DLL.
Generally though, everything looks fine, and the first IAT entry points to my stubs. The code then iterates through all the stubs for the DLL. At each stub, the value of the stub's count field is added to a running total for the DLL. When the iteration completes, ReportProfileResults formats a string with the name of the DLL and how many calls were made through the stubs. The code uses OutputDebugString to broadcast its findings.


Loading and Injection
The program that loads your EXE and injects DelayLoadProfileDLL.DLL is called—you guessed it—DelayLoadProfile.EXE (the source code is available from the MSJ Web site at http://www.microsoft.com/msj). This code mainly drives the CDebugInjector class, which I'll describe shortly. Function main obtains the target EXE's command line and passes it to CDebugInjector::LoadProcess. If the process is created successfully, function main tells CDebugInjector which DLL it wants injected. In this case, it's DelayLoadProfileDLL.DLL, which should be located in the same directory as DelayLoadProfile.EXE.
The last step before letting the target run wild is to call CDebugInjector::SetOutputDebugStringCallback. When DelayLoadProfileDLL reports its results via OutputDebugString, CDebugInjector sees them and passes them to the callback you registered. This callback just printfs the strings to the console. Finally, function main calls CDebugInjector::Run. This call lets the target process begin and, when the time is right, injects the DLL into it.
Figure 3 shows The CDebugInjector class. This is where all the good stuff happens. CDebugInjector::LoadProcess creates the specified process as a debugee process. The ramifications of running as a debugee process have been discussed in many articles and in the MSDN documentation, so I won't go into all the details here.
For the purposes of this column, it's sufficient to say that the debugger process (in this case, DelayLoadProfile) has to enter a loop that calls WaitForDebugEvent and ContinueDebugEvent until the debugee terminates. Every time WaitForDebugEvent returns, something has happened in the debugee. This might be an exception (including break—points), a DLL load, a thread creation, or other event. The WaitForDebugEvent documentation covers all the events that might occur. The CDebugInjector::Run method contains the code for this loop.
So how does running the target process as a debugee help you inject a DLL? A debugger process has excellent control over the debugee process's execution. Every time a significant event occurs in the debugee, it is suspended until the debugger calls ContinueDebugEvent. Knowing this, a debugger process can add code to the debugee's address space and temporarily change the debugee's registers so that the added code executes.
In more specific terms, CDebugInjector synthesizes a small code stub that calls LoadLibrary. The DLL name parameter to LoadLibrary points to the name of the DLL to inject. CDebugInjector writes the stub (and the associated DLL name) to the debugee's address space. It then calls SetThreadContext to change the debugee's instruction pointer (EIP) to execute the LoadLibrary stub. All of this dirty work occurs within the CDebugInjector::PlaceInjectionStub method.
Immediately following the LoadLibrary call in the stub is a breakpoint instruction (INT 3). This stops the debugee and gives control back to the debugger process. The debugger then uses SetThreadContext again to restore the instruction pointer and other registers to their original values. Another call to ContinueDebugEvent and the debugee is on its way with the DLL injected, none the wiser that anything has happened.
If you don't think too hard, this injection process doesn't sound too messy. Nonetheless, a few interesting problems crop up that complicate things. For example, when is the proper time to create the stub code and redirect control to it? You can't do this immediately after the CreateProcess call because, among other reasons, the imported DLLs haven't been mapped into memory at this point and the EXE's IAT hasn't been fixed up by the Win32 loader. In other words, it's too early.
The solution I ultimately decided on was to let the debugee run until it encounters its first breakpoint. Then I set a breakpoint of my own at the entry point of the EXE. When this second breakpoint triggers, CDebugInjector knows that DLLs in the target process (including KERNEL32.DLL) have initialized, but no code in the EXE has run. This is the perfect time for injecting DelayLoadProfileDLL.DLL.
Incidentally, where does the first breakpoint come from? By definition, a Win32 process that's being debugged calls DebugBreak (also known as INT 3) very early in its execution. In my ancient APISPY32 code, I used the initial DebugBreak as the occasion to do the injection. Unfortunately in Windows 2000, this DebugBreak occurs before KERNEL32.DLL is initialized. Thus, CDebugInjector sets its own breakpoint to go off when the EXE is about to get control, and thus knows that KERNEL32.DLL has been initialized.
Earlier, I mentioned a breakpoint that occurs after the LoadLibrary call returns. This is a third breakpoint for CDebugInjector to handle. All of the mechanics for handling the different breakpoints can be seen in CDebugInjector::HandleException.
Another interesting problem to address with DLL injection is where to write the LoadLibrary stub. Under Windows NT 4.0 and later you can allocate space in another process with VirtualAllocEx, so I took that route. That leaves out Windows 9x, which doesn't support VirtualAllocEx. For this scenario, I took advantage of a unique property of Windows 9x memory-mapped files. These files are visible in all address spaces, and at the same address. I simply create a small memory-mapped file using the system page file as backing, and blast the LoadLibrary stub into it. The stub is implicitly accessible in the debugee process. For the details, see the code listing for CDebugInjector::GetMemoryForLoadLibraryStub at the link at the top of this article.


Using DelayLoadProfile
DelayLoadProfile is a command-line program that writes its results to standard output. From a command prompt, run DelayLoadProfile, specifying the target program and any arguments it needs, such as:

DelayLoadProfile notepad c:\autoexec.bat


Here are the results of running DelayLoadProfile against CALC.EXE from Windows 2000 Release Candidate 2:
[d:\column\col66\debug]delayloadprofile calc
DelayLoadProfile: SHELL32.dll was called 0 times
DelayLoadProfile: MSVCRT.dll was called 9 times
DelayLoadProfile: ADVAPI32.dll was called 0 times
DelayLoadProfile: GDI32.dll was called 60 times
DelayLoadProfile: USER32.dll was called 691 times


I simply started CALC and immediately shut it down. Note that SHELL32.DLL and ADVAPI32.DLL both had no calls to them. These two DLLs are prime candidates for CALC to DelayLoad.
You may be wondering why CALC loads SHELL32.DLL, yet doesn't call it. It would be easy enough to run DumpBin /IMPORTS or Depends.EXE against CALC. In doing so, you'd see that the only function CALC imports from SHELL32.DLL is ShellAboutW. Simply put, unless you select the Help | About Calculator menu item in CALC, it's a complete waste of time and memory to load SHELL32.DLL. This is a fabulous example of where /DELAYLOAD can really show its worth. Incidentally, SHELL32.DLL implicitly links against SHLWAPI.DLL and COMCTL32.DLL—two additional DLLs that are brought into memory and initialized for no reason.
Just because DelayLoadProfile reports that a DLL is receiving few or no calls at all doesn't mean you should automatically DelayLoad it. Be sure to consider whether one of your implicitly linked DLLs also links against the DLL you're considering using DelayLoad with. If this is the case, it's not worth using /DELAYLOAD in your EXE since the DLL is still going to be loaded and initialized because of some other dependency. Depends.EXE from the Platform SDK is a great tool for quickly determining the scope of a DLL's usage.
Another thing to consider when using DelayLoadProfile is how much of your app you'll exercise during your test. Obviously, if you exercise all aspects of your app, all the DLLs you import in the EXE will be invoked. Personally, I think minimal load time is a good target to shoot for. This might mean just starting your program and then closing it down. By spreading the work of loading and initializing your DLLs throughout your application as it runs, you can speed the initial load sequence. Users often subjectively judge the speed of your application by its startup time.
I've found a few DLLs that will benefit from using /DELAYLOAD. As you saw earlier, SHELL32.DLL is one of them. Another is WINSPOOL.DRV, which is used for printing support. Since most users don't print frequently, it's a good candidate, as are OLE32.DLL and OLEAUT32.DLL. In addition, a variety of programs use COM and OLE in some minimal capacity, making those DLLs possible candidates, too. For example, the Windows 2000 CDPLAYER.EXE links against OLE32.DLL and the CreateStreamOnHGlobal API. Yet in ordinary usage, I didn't observe this function being called.
DelayLoadProfile is not without its faults (literally). While I've tested it successfully with a large number of applications, you may still run into the occasional program that doesn't work so well when DelayLoadProfileDLL interfaces with its IAT. Trying to find and locate all these odd scenarios is beyond the scope of this column. However, if you locate and fix one of these problems, please let me know. I may update DelayLoadProfile at some future date.
I know that programs that import MFC42.DLL and MFC42U.DLL can crash with DelayLoadProfile. For that reason I've provided an escape hatch. In DelayLoadProfileDLL.CPP it's the IsModuleOKToHook function. I've placed MFC42.DLL, MFC42U.DLL, and KERNEL32.DLL in it. (You can't use /DELAYLOAD with KERNEL32.DLL anyhow, so it's no loss.) If a particular DLL seems to be giving you problems, first try adding it to IsModuleOKToHook.
I hope DelayLoadProfile's ease of use will inspire you to tune your applications to make use of /DELAYLOAD. I certainly had a good time updating some classic code, and I'd enjoy hearing your success stories, too.



Have a suggestion for Under The Hood? Send it to Matt at [email protected] or http://www.tiac.com/users/mpietrek.



From the February 2000 issue of Microsoft Systems Journal.

mk:@MSITStore:\Program\Microsoft%20Visual%20Stud io\MSDN\2001JUL\1033\period00.chm::/html/hood0200.htm
Digital is offline  
Old 23.05.2005, 13:14   #25
Digital
Архивный участник
 
Join Date: Nov 2004
Posts: 1,405
Default

seems to me them chinese did it again... lol
with a l2hook.dll

struct caller_stub {
BYTE instr_PUSHA; /* Save all registers */
BYTE instr_PUSH; /* Push the address of the "L2hook.dll" string */
DWORD operand_PUSH; /* To be filled later */
BYTE instr_MOV_EAX; /* Mov the address of the loadlibraryA proc */
DWORD operand_MOV_EAX; /* To be filled later */
WORD instr_CALL_EAX; /* Call the library */
BYTE instr_POPA; /* Restore the registers */
BYTE instr_PUSH2; /* Push the new eip */
DWORD operand_PUSH2;
BYTE instr_RET; /* Return to the program - to the new eip */
BYTE data[11]; /* To store the dll name */

caller_stub():
instr_PUSHA(0x60),
instr_PUSH(0x68),
instr_MOV_EAX(0xB8),
instr_CALL_EAX(0xD0FF),
instr_POPA(0x61),
instr_PUSH2(0x68),
operand_PUSH2(0x00063DA60), // Not right
instr_RET(0xc3)
{
/* L2hook.dll - name of the file we load */
data[0] = 'L'; data[1] = '2'; data[2] = 'h';
data[3] = 'o'; data[4] = 'o'; data[5] = 'k';
data[6] = '.'; data[7] = 'd'; data[8] = 'l';
data[9] = 'l'; data[10]= 0;
}
};

我有几个问题,请知道的指点一下:
1. operand_PUSH2(0x00063DA60), // Not right
这个返回地址到底应该是多少,怎样� �找?

2. operand_PUSH 指向的是DLL路径字符串的地址,
stub_struct.operand_PUSH = (DWORD)memory + sizeof(caller_stub) - 12;
照理讲应该是 - 11才对阿, 为什么是12

3 WriteProcessMemory(pi.hProcess, (LPVOID)LOADER_CallerAddr, &offs, 4, &nbytes)
LOADER_CallerAddr是怎么确定的.
代码的意思应该是先jump到 stub_struct. 那么把这个offs写入这个地址, 在LOADER_CallerAddr之前是一个Jump指令?

能给我解释一下,十分感谢. 如果怕麻烦,告诉我看那些资料,也同样 感谢
Digital is offline  
 

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT. The time now is 17:03.