HOOK VirtualProtectEx(hProc,fproc,5,dwIdOld,&dwIdOld)

默认分类   2008-12-17 21:25   阅读163   评论0  
字号:    

Clock.obj : error LNK2001: unresolved external symbol "public: static struct CRuntimeClass const CClockView::classCClockView" (?classCClockView@CClockView@@2UCRuntimeClass@@B)

#INCLUDE "stdafx.h"
原因是文件被删除了
需要重新回复工程
============================
社区焦点x
发过节费-澳门回归纪念
SD2社区专家沙龙照片花絮
SQL注入专题--整理帖
读《疯狂的程序员》有感
中文乱码的处理办法
首页 新闻 论坛 群组 Blog 文档 下载 读书 Tag 网摘 搜索 .NET Java 游戏 视频 人才 外包 培训 数据库 书店 程序员

 欢迎您:afdfewr434543 | 退出 | 登录 注册 帮助
我的帖子我参与的帖子我的空间我的网摘
 
   CSDNCSDN社区VC/MFC进程/线程/DLL将帖子提前   放进我的网摘   推荐给好友 我要提问 帖子加分 生成帖子 置顶 推荐(加精) 取消推荐(加精) 锁定帖子 移动帖子 取消引用结帖去... 管理菜单 页面风格切换标准风格老版本论坛  我截获了 ZwCreateFile函数,但是未得到预想的效果,请高人指点  [已结帖,结帖人:howdoesitfeel]
 
 加为好友
发送私信
在线聊天
howdoesitfeel
HowDoesItFeel
等级:
可用分等级:长工
总技术分:2
总技术分排名:285337
结帖率:100.00%

 发表于:2007-04-24 10:24:30 楼主
我的目的是想截获用户创建文件,删除文件等操作,并能由程序决定这些操作能否成功执行.我知道SHChangeNotifyRegister,ReadDirectoryChanges可以捕获这些事件,但是仅仅只能知道发生了这些事件,而不能控制.所以想用HOOK   Api的方法试试.
        我用全局WH_GETMESSAGE和IAT方法来HOOK   ZwCreateFile,我调试的时候发现确实跳转到了我自己的MyZwCreateFile,但是很奇怪,通过在MyZwCreateFile输出的日志中我发现只能截获到一种的信息:[System]进程对   [\??\PIPE\lsarpc]调用了ZwCreateFile.
        是不是仅仅拦截ZwCreateFile还不行?那么我该拦截哪些API呢,CreateFileW我也拦截过了,同样只能截获到很少的信息量,我自己新建一个文档,程序毫无反应.

代码:
//---------------------------------------------------------------
#include   <windows.h>
#include   "DdkDef.h "
#pragma   hdrstop
//---------------------------------------------------------------------------


#pragma   argsused

#define   WM_X_CRTFL_W   (WM_APP+0X177)       //CreatrFileW   Notify
#define   WM_X_CRTFL_A   (WM_APP+0X178)       //CreatrFileA   Notify
#define   WM_X_CRTFL_Z   (WM_APP+0X179)       //ZwCreatrFile   Notify

#define   _TEST_ONLY
#define   HOOK_ZW_ONLY
//#define   HOOK_ANSI
//#define   _TEST_NOHOOK_SYSPROC
//#define   _TEST_FILTER_FILES
#ifdef   _TEST_ONLY
unsigned   long   iCount=0;
#endif

pZW_CREATE_FILE   ZwCreateFileFunc;

COPYDATASTRUCT   CopyData;
HHOOK   f_Hook=NULL;
HINSTANCE   f_hinstDll;
HMODULE   hModule=NULL;
HMODULE   hModule2=NULL;
FARPROC   f_farCreateFileW;
FARPROC   f_farCreateFileA;
FARPROC   f_farZwCreateFile;
BYTE   OldCreateFileWCode[5],NewCreateFileWCode[5];
BYTE   OldCreateFileACode[5],NewCreateFileACode[5];
BYTE   OldZwCreateFileCode[5],NewZwCreateFileCode[5];
bool   bCrtFWHooked;
bool   bCrtFAHooked;
bool   bZwCrtFHooked;
bool   bAllHooked;
DWORD   dwIdOld,dwIdNew;
HWND   hWndApp=NULL;
WCHAR   strLastFileNameW[MAX_PATH+1]     ;
char     strLastFileNameA[MAX_PATH+1]     ;
HANDLE   MyCreateFileW(
    LPCWSTR   lpFileName,
    DWORD   dwDesiredAccess,
    DWORD   dwShareMode,
    LPSECURITY_ATTRIBUTES   lpSecurityAttributes,
    DWORD   dwCreationDisposition,
    DWORD   dwFlagsAndAttributes,
    HANDLE   hTemplateFile
);
  HANDLE   MyCreateFileA(
    LPCSTR   lpFileName,
    DWORD   dwDesiredAccess,
    DWORD   dwShareMode,
    LPSECURITY_ATTRIBUTES   lpSecurityAttributes,
    DWORD   dwCreationDisposition,
    DWORD   dwFlagsAndAttributes,
    HANDLE   hTemplateFile
);
NTSTATUS   MyZwCreateFile(
OUT   PHANDLE     FileHandle,
        IN   ACCESS_MASK     DesiredAccess,
        IN   POBJECT_ATTRIBUTES     ObjectAttributes,
        OUT   PIO_STATUS_BLOCK     IoStatusBlock,
        IN   PLARGE_INTEGER     AllocationSize     OPTIONAL,
        IN   ULONG     FileAttributes,
        IN   ULONG     ShareAccess,
        IN   ULONG     CreateDisposition,
        IN   ULONG     CreateOptions,
        IN   PVOID     EaBuffer     OPTIONAL,
        IN   ULONG     EaLength
);

bool   __fastcall   InstallHook();
bool   __fastcall   UninstallHook();
bool   __fastcall   InitHookAPI();
DWORD   __fastcall   InsertMyFuncs();
DWORD   __fastcall   RestoreOSFuncs();
DWORD     __fastcall   InsertAFunc   (FARPROC*   fproc,BYTE   *JumpNew);
DWORD     __fastcall   RestoreAFunc(FARPROC*   fproc,BYTE   *JumpOld);
LRESULT   WINAPI   NullHookProc(int   nCode,WPARAM   wParam,LPARAM   lParam);
extern   "C "   __declspec(dllexport)   void   __stdcall   xStart(HWND   hWnd);
extern   "C "   __declspec(dllexport)   __stdcall   void   xStop();
//---------------------------------------------------------------------------
int   WINAPI   DllEntryPoint(HINSTANCE   hinst,   unsigned   long   reason,   void*   lpReserved)
{
if(reason==DLL_PROCESS_ATTACH)
{
//
f_hinstDll=hinst;


}
if(reason==DLL_PROCESS_DETACH)
{
if(bAllHooked)
RestoreOSFuncs();
UninstallHook();
if(hModule)
{
FreeLibrary(hModule);
hModule=NULL;
}
if(hModule2)
{
FreeLibrary(hModule2);
hModule=NULL;
}
}
return   1;
}
//---------------------------------------------------------------------------
void   __stdcall   xStart(HWND   hWnd)
{
hWndApp=hWnd;
InstallHook();
if(!bAllHooked   &&   InitHookAPI())
InsertMyFuncs();
}
void   __stdcall   xStop()
{
if(bAllHooked)
RestoreOSFuncs();
if(f_Hook)
{
UninstallHook();
f_Hook=NULL;
}
if(hModule2)
{
FreeLibrary(hModule2);
hModule2=NULL;
}
}
 
 
 
问题点数:100 回复次数:11 显示所有回复显示星级回复显示楼主回复 修改 删除 举报 引用 回复  
 

 加为好友
发送私信
在线聊天
 howdoesitfeel
HowDoesItFeel
等级:
可用分等级:长工
总技术分:2
总技术分排名:285337

 发表于:2007-04-24 10:25:451楼 得分:0
char  bl   =0xb8;
int address;
char mveax[3]={0xff,0xe0,0x0};
/*JmpCode.JmpCode := $B8;
  JmpCode.MovEAX[0] := $FF;
  JmpCode.MovEAX[1] := $E0;
  JmpCode.MovEAX[2] := 0;
  */
bool   __fastcall   InitHookAPI()
{
hModule=LoadLibrary( "Kernel32.dll ");
f_farCreateFileW=GetProcAddress(hModule, "CreateFileW ");
f_farCreateFileA=GetProcAddress(hModule, "CreateFileA ");
hModule2=LoadLibrary( "ntdll.dll ");
f_farZwCreateFile=GetProcAddress(hModule2, "ZwCreateFile ");
if(f_farCreateFileW==NULL   ||   f_farCreateFileA==NULL   ||   f_farZwCreateFile==NULL)
return   false;
ZwCreateFileFunc=   (pZW_CREATE_FILE)f_farZwCreateFile;
//CreateFileW
_asm
{
lea   edi,OldCreateFileWCode
mov   esi,f_farCreateFileW
cld
movsd
movsb
}
NewCreateFileWCode[0]=0xe9;
_asm
{
lea   eax,MyCreateFileW
mov   ebx,f_farCreateFileW
sub   eax,ebx
sub   eax,5
mov   dword   ptr   [NewCreateFileWCode+1],eax
}
//CreateFileA
_asm
{
lea   edi,OldCreateFileACode
mov   esi,f_farCreateFileA
cld
movsd
movsb
}
NewCreateFileACode[0]=0xe9;
_asm
{
lea   eax,MyCreateFileA
mov   ebx,f_farCreateFileA
sub   eax,ebx
sub   eax,5
mov   dword   ptr   [NewCreateFileACode+1],eax
}
//ZwCreateFile
_asm
{
lea   edi,OldZwCreateFileCode
mov   esi,f_farZwCreateFile
cld
movsd
movsb
}
NewZwCreateFileCode[0]=0xe9;
_asm
{
lea   eax,MyZwCreateFile
mov   ebx,f_farZwCreateFile
sub   eax,ebx
sub   eax,5
mov   dword   ptr   [NewZwCreateFileCode+1],eax
}
dwIdNew=GetCurrentProcessId();   //得到所属进程的ID
#ifdef   _TEST_NOHOOK_SYSPROC
if(dwIdNew <100)
        return   false;
#endif
dwIdOld=dwIdNew;
//InsertMyFuncs();//开始拦截
        return   true;  
}

DWORD     __fastcall   InsertAFunc   (FARPROC   fproc,BYTE   *JumpNew)
{
HANDLE   hProc;
dwIdOld=dwIdNew;
bool   dwRet=0;
hProc=OpenProcess(PROCESS_ALL_ACCESS,0,dwIdOld);//得到所属进程的句柄
if(hProc==NULL)
return   GetLastError();
dwRet=VirtualProtectEx(hProc,fproc,5,PAGE_READWRITE,&dwIdOld);
if(!dwRet)
return   GetLastError();
dwRet=WriteProcessMemory(hProc,fproc,JumpNew,5,0);
if(!dwRet)
return   GetLastError();
dwRet=VirtualProtectEx(hProc,fproc,5,dwIdOld,&dwIdOld);
if(!dwRet)
return   GetLastError();
//bHooked=true;
return   0;
}
DWORD     __fastcall   RestoreAFunc(FARPROC   fproc,BYTE   *JumpOld)
{
HANDLE   hProc;
dwIdOld=dwIdNew;
bool   dwRet=0;
hProc=OpenProcess(PROCESS_ALL_ACCESS,0,dwIdOld);
if(hProc==NULL)
return   GetLastError();
dwRet=VirtualProtectEx(hProc,fproc,5,PAGE_READWRITE,&dwIdOld);
if(!dwRet)
return   GetLastError();
dwRet=WriteProcessMemory(hProc,fproc,JumpOld,5,0);
if(!dwRet)
return   GetLastError();
dwRet=VirtualProtectEx(hProc,fproc,5,dwIdOld,&dwIdOld);
if(!dwRet)
return   GetLastError();
//bHooked=false;
return   0;
}

DWORD   __fastcall   InsertMyFuncs()
{
DWORD   ret;
#ifndef     HOOK_ZW_ONLY
ret=InsertAFunc(f_farCreateFileW,NewCreateFileWCode);
if(ret!=0)
return   ret;
else
bCrtFWHooked=true;
#ifdef   HOOK_ANSI
ret=InsertAFunc(f_farCreateFileA,NewCreateFileACode);
if(ret!=0)
return   ret;
else
bCrtFAHooked=true;
//if(bCrtFAHooked)
#endif
#endif
ret=InsertAFunc(f_farZwCreateFile,NewZwCreateFileCode);
if(ret!=0)
return   ret;
else
bZwCrtFHooked=true;
bAllHooked   =   true;
return   0;

}  
DWORD   __fastcall   RestoreOSFuncs()
{
DWORD   ret;
#ifndef     HOOK_ZW_ONLY
ret=RestoreAFunc(f_farCreateFileW,OldCreateFileWCode);
if(ret!=0)
return   ret;
else
bCrtFWHooked=false;
#ifdef   HOOK_ANSI
ret=RestoreAFunc(f_farCreateFileA,OldCreateFileACode);
if(ret!=0)
return   ret;
else
bCrtFAHooked=false;
#endif
#endif
ret=RestoreAFunc(f_farZwCreateFile,OldZwCreateFileCode);
if(ret!=0)
return   ret;
else
bZwCrtFHooked=false;
bAllHooked   =   false;
return   0;
}

LRESULT   WINAPI   NullHookProc(int   nCode,WPARAM   wParam,LPARAM   lParam)//空的钩子函数
{  

return(CallNextHookEx(f_Hook,nCode,wParam,lParam));
}  
bool   __fastcall   InstallHook()
{

f_Hook=SetWindowsHookEx(WH_GETMESSAGE,(HOOKPROC)NullHookProc,f_hinstDll,0);
if   (!f_Hook)
{
//MessageBoxA(NULL, "SET   ERROR ", "ERROR ",MB_OK);
return   false   ;
}


return   true;
}  
bool   __fastcall   UninstallHook()//输出御在钩子函数
{  

        return(UnhookWindowsHookEx(f_Hook));
}
 
修改 删除 举报 引用 回复  
 
 加为好友
发送私信
在线聊天
 howdoesitfeel
HowDoesItFeel
等级:
可用分等级:长工
总技术分:2
总技术分排名:285337

 发表于:2007-04-24 10:26:082楼 得分:0

HANDLE   MyCreateFileW(LPCWSTR   lpFileName,DWORD   dwDesiredAccess,DWORD   dwShareMode,LPSECURITY_ATTRIBUTES   lpSecurityAttributes,DWORD   dwCreationDisposition,DWORD   dwFlagsAndAttributes,HANDLE   hTemplateFile)
{
RestoreAFunc(f_farCreateFileW,OldCreateFileWCode);
HANDLE   handle;
handle=CreateFileW(lpFileName,dwDesiredAccess,dwShareMode,lpSecurityAttributes,   dwCreationDisposition,   dwFlagsAndAttributes,   hTemplateFile);

#ifdef   _TEST_ONLY
bool   bSend     ;
int   i=1;

if(i==1/*!wcscmp(lpFileName,strLastFileNameW*/
#ifdef   _TEST_FILTER_FILES
&&   wcslen(lpFileName)> 20
#endif
)
{
                if(iCount> 0xFFFFFFFF)
                        iCount=0;
iCount++;
//#pragma   warn   -8004
//bSend=PostMessage(HWND_BROADCAST,WM_X_CRTFL,dwIdOld,iCount);
bSend=PostMessage(hWndApp,WM_X_CRTFL_W,dwIdOld,iCount);
                //#pragma   warn   +8004
}
wcscpy(strLastFileNameW,lpFileName);

#else
      // InsertMyFuncs();
      // return   CreateFileW(lpFileName,dwDesiredAccess,dwShareMode,lpSecurityAttributes,   dwCreationDisposition,   dwFlagsAndAttributes,   hTemplateFile);
#endif
InsertAFunc(f_farCreateFileW,NewCreateFileWCode);
return     handle;
}

HANDLE   MyCreateFileA(LPCSTR   lpFileName,DWORD   dwDesiredAccess,DWORD   dwShareMode,LPSECURITY_ATTRIBUTES   lpSecurityAttributes,DWORD   dwCreationDisposition,DWORD   dwFlagsAndAttributes,HANDLE   hTemplateFile)
{
RestoreAFunc(f_farCreateFileA,OldCreateFileACode);
HANDLE   handle;
handle=CreateFileA(lpFileName,dwDesiredAccess,dwShareMode,lpSecurityAttributes,   dwCreationDisposition,   dwFlagsAndAttributes,   hTemplateFile);
#pragma   warn   -8066
#ifdef   _TEST_ONLY
bool   bSend     ;
int   i=1;
//handle=CreateFileW(lpFileName,dwDesiredAccess,dwShareMode,lpSecurityAttributes,   dwCreationDisposition,   dwFlagsAndAttributes,   hTemplateFile);
if(i==1/*!wcscmp(lpFileName,strLastFileNameA*/
#ifdef   _TEST_FILTER_FILES
&&   wcslen(lpFileName)> 20
#endif
)
{
                if(iCount> 0xFFFFFFFF)
                        iCount=0;
iCount++;
//#pragma   warn   -8004
bSend=PostMessage(hWndApp,WM_X_CRTFL_A,dwIdOld,iCount);
//PostMessage(hWndApp,WM_X_CRTFL,dwIdOld,iCount);
                //#pragma   warn   +8004
}
strcpy(strLastFileNameA,lpFileName);

#else
      // InsertMyFuncs();
      // return   CreateFileW(lpFileName,dwDesiredAccess,dwShareMode,lpSecurityAttributes,   dwCreationDisposition,   dwFlagsAndAttributes,   hTemplateFile);
#endif
InsertAFunc(f_farCreateFileA,NewCreateFileACode);
return     handle;
#pragma   warn   +8066
}

NTSTATUS   MyZwCreateFile(
OUT   PHANDLE     FileHandle,                                                                 //     1
IN   ACCESS_MASK     DesiredAccess,                                                     //     2
IN   POBJECT_ATTRIBUTES     ObjectAttributes,                                 //     3
OUT   PIO_STATUS_BLOCK     IoStatusBlock,                                         //     4
IN   PLARGE_INTEGER     AllocationSize     OPTIONAL,                         //     5
IN   ULONG     FileAttributes,                                                               //     6
IN   ULONG     ShareAccess,                                                                     //     7
IN   ULONG     CreateDisposition,                                                         //     8
IN   ULONG     CreateOptions,                                                                 //     9
IN   PVOID     EaBuffer     OPTIONAL,                                                       //     10
IN   ULONG     EaLength                                                                             //     11
)
{

//return   CreateFileA(lpFileName,dwDesiredAccess,dwShareMode,lpSecurityAttributes,   dwCreationDisposition,   dwFlagsAndAttributes,   hTemplateFile);


#pragma   warn   -8066
#ifdef   _TEST_ONLY
bool   bSend     ;
int   i=1;
if(i==1/*!wcscmp(lpFileName,strLastFileNameA*/
#ifdef   _TEST_FILTER_FILES
&&   wcslen(ObjectAttributes-> ObjectName   )> 4
#endif
)
{
if(iCount> 0xFFFFFFFF)
iCount=0;
iCount++;
//#pragma   warn   -8004
//bSend=PostMessage(HWND_BROADCAST,WM_X_CRTFL,dwIdOld,iCount);
bSend=PostMessage(hWndApp,WM_X_CRTFL_Z,dwIdOld,iCount);
//#pragma   warn   +8004
}

wcscpy(strLastFileNameW,ObjectAttributes-> ObjectName-> Buffer);
CopyData.dwData=0;
CopyData.lpData=strLastFileNameW;
CopyData.cbData=sizeof(CopyData);
bSend=SendMessage(hWndApp,WM_COPYDATA,0x77,(LPARAM)   (LPVOID)   &CopyData);
#else
      // InsertMyFuncs();
      // return   CreateFileW(lpFileName,dwDesiredAccess,dwShareMode,lpSecurityAttributes,   dwCreationDisposition,   dwFlagsAndAttributes,   hTemplateFile);
#endif
        RestoreAFunc(f_farZwCreateFile,OldZwCreateFileCode);
NTSTATUS   ntstatus;
ntstatus=ZwCreateFileFunc(FileHandle,
DesiredAccess,
ObjectAttributes,
IoStatusBlock,
AllocationSize,
FileAttributes,
ShareAccess   ,
CreateDisposition,
CreateOptions,
EaBuffer,
EaLength
);
InsertAFunc(f_farZwCreateFile,NewZwCreateFileCode);
return     ntstatus;
#pragma   warn   +8066
}
 
修改 删除 举报 引用 回复  
 
 加为好友
发送私信
在线聊天
 KeSummer
[IN]LPVOID YourLove,[OUT]LPVOID MyLove
等级:
可用分等级:富农
总技术分:10446
总技术分排名:1867

 发表于:2007-04-24 13:22:223楼 得分:10
拦截的就是ZwCreateFile,ZwCreateFile并非简单的创建磁盘文件那么简单,它还可以创建一些内核对象.参考DDK里面的说明.

可以先用windbg对ntdll!ZwCreateFile下断,看一下栈就行了.
 
修改 删除 举报 引用 回复  
 
 加为好友
发送私信
在线聊天
 CathySun118
失.悟
等级:
可用分等级:富农
总技术分:84841
总技术分排名:67
2
 发表于:2007-04-24 14:57:014楼 得分:0
太长了,帮顶吧
 
修改 删除 举报 引用 回复  
 
 加为好友
发送私信
在线聊天
 systemthink
think_e_r_d
等级:
可用分等级:富农
总技术分:2797
总技术分排名:7724

 发表于:2007-04-24 19:41:155楼 得分:0
这么长怎么看呀?

难道说你是 "gubinary "变种?
 
修改 删除 举报 引用 回复  
 
 加为好友
发送私信
在线聊天
 BeRoy
不主动,不拒绝,不负责.
等级:
可用分等级:富农
总技术分:2755
总技术分排名:7766

 发表于:2007-04-25 16:53:026楼 得分:0
HWND   hWndApp   应该用共享内存
 
修改 删除 举报 引用 回复  
 
 加为好友
发送私信
在线聊天
 nf3
 
等级:
可用分等级:富农
总技术分:369
总技术分排名:40523

 发表于:2007-04-26 13:30:397楼 得分:60
HOOK   API的方法是行不通的,
有些CreateFile的API微软没有公开;
只能用驱动的方法拦截.
 
修改 删除 举报 引用 回复  
 
 加为好友
发送私信
在线聊天
 sirguan
123
等级:
可用分等级:中农
总技术分:1266
总技术分排名:16160

 发表于:2007-04-26 13:37:238楼 得分:10
利用softice对zwcreatefile下个断点看看就知道了
 
修改 删除 举报 引用 回复  
 
 加为好友
发送私信
在线聊天
 zzz3265
Yofoo
等级:
可用分等级:富农
总技术分:17787
总技术分排名:738

 发表于:2007-05-02 21:59:489楼 得分:10
我在公司就用API   Hook的方式实现你想的类似功能
ZwCreatefile   ,   另外还有   ZwOpenFile,
我以实现
 
修改 删除 举报 引用 回复  
 
 加为好友
发送私信
在线聊天
 LookSail
老得牙都掉了还在学
等级:
可用分等级:掌柜
总技术分:4673
总技术分排名:4482

 发表于:2007-05-06 22:25:2810楼 得分:10
如果在驱动里面做用filter,去驱网看帖子

如果在应用层做,Hook     CreateFileA,CreateFileW,DeleteFile就可以了,不需要Hook   ZwCreateFile

目前我的软件也是全局WH_GETMESSAGE和IATHook,Hook了比这多的多的API,工作很正常,基本上都能拦截到,拦截不到也是系统的一些底层操作,恰恰这些我不需要拦截

你拦截不到说明你的代码或思路问题,而不是HookAPI的技术方案不行,去看Windows核心编程吧
 
修改 删除 举报 引用 回复  
 
 加为好友
发送私信
在线聊天
 howdoesitfeel
HowDoesItFeel
等级:
可用分等级:长工
总技术分:2
总技术分排名:285337

 发表于:2007-05-10 15:03:4511楼 得分:0
多谢大家提醒,我的代码确实有很多问题,主要是我自己思路还不是很清晰,DLL的有些变量应该为全局的(在每个进程中都能访问到),我修改了一下,用共享内存来保存全局变量.然后在空的钩子回调函数里面做一次插入用来将所有勾到的进程中的CreatFileW替换:
LRESULT   WINAPI   NullHookProc(int   nCode,WPARAM   wParam,LPARAM   lParam)//空的钩子函数
{

if(bFirst==true)
{

dwCurrentProc=   GetCurrentProcessId();
InitHookAPI();
SendMessage(*hWndApp,WM_X_DEB,GetCurrentThreadId(),2);
DWORD   dwRet=InsertMyFuncs(dwCurrentProc);
if(dwRet)//成功
SendMessage(*hWndApp,WM_X_DEB,dwRet,30);
bFirst=false;
}


return(CallNextHookEx(f_Hook,nCode,wParam,lParam));
}
//自定义的CreateFileW函数
HANDLE   MyCreateFileW(LPCWSTR   lpFileName,DWORD   dwDesiredAccess,DWORD   dwShareMode,LPSECURITY_ATTRIBUTES   lpSecurityAttributes,DWORD   dwCreationDisposition,DWORD   dwFlagsAndAttributes,HANDLE   hTemplateFile)
{
HANDLE   handle=NULL;
try
{
EnterCriticalSection(&pGMem-> LockW);//pGMem,hWndApp在共享内存中
SendMessage(*hWndApp,WM_X_DEB,dwCurrentProc,1001);


//handle=CreateFileW(lpFileName,dwDesiredAccess,dwShareMode,lpSecurityAttributes,   dwCreationDisposition,   dwFlagsAndAttributes,   hTemplateFile);
#ifdef   _TEST_ONLY
bool   bSend     ;

wcscpy(strLastFileNameW,lpFileName);
strLastFileNameW[MAX_PATH]= '\0\0 ';
CopyData.dwData=0;
CopyData.lpData=strLastFileNameW;
CopyData.cbData=sizeof(CopyData);
bSend=SendMessage(*hWndApp,WM_COPYDATA,0x77,(LPARAM)   (LPVOID)   &CopyData);
#else
      // InsertMyFuncs();
      // return   CreateFileW(lpFileName,dwDesiredAccess,dwShareMode,lpSecurityAttributes,   dwCreationDisposition,   dwFlagsAndAttributes,   hTemplateFile);
#endif
RestoreAFunc(/*pGMem->   */f_farCreateFileW,/*pGMem->   */OldCreateFileWCode,dwCurrentProc);
handle=CreateFileW(lpFileName,dwDesiredAccess,dwShareMode,lpSecurityAttributes,   dwCreationDisposition,   dwFlagsAndAttributes,   hTemplateFile);
InsertAFunc(/*pGMem->   */f_farCreateFileW,/*pGMem->   */NewCreateFileWCode,dwCurrentProc);
}
catch(...)
{
SendMessage(*hWndApp,WM_X_DEB,dwCurrentProc,1002);
LeaveCriticalSection(&pGMem-> LockW);
throw;
}

SendMessage(*hWndApp,WM_X_DEB,dwCurrentProc,40);
LeaveCriticalSection(&pGMem-> LockW);
return     handle;
}
//修改跳转指令的函数在这里:
DWORD     __fastcall   InsertAFunc   (FARPROC   fproc,BYTE   *JumpNew,DWORD   dwProcID)
{

HANDLE   hProc;
DWORD   dwNewProtect;
DWORD   dwOldProtect;


//SendMessage(hWndApp,WM_X_DEB,GetCurrentThreadId()/*GetCurrentProcessId()*/,3);
SendMessage(*hWndApp,WM_X_DEB,dwProcIDRpt,3);
bool   dwRet=0;
hProc=OpenProcess(PROCESS_ALL_ACCESS,0,dwProcID);//得到所属进程的句柄
if(hProc==NULL)
{
DWORD   err=   GetLastError();

return     err;
}
dwRet=VirtualProtectEx(hProc,fproc,5,PAGE_READWRITE,&dwOldProtect);//修改所属进程前5个字节的属性为可写
if(!dwRet)
{
DWORD   err=   GetLastError();

return     err;
}
dwRet=WriteProcessMemory(hProc,fproc,JumpNew,5,0);//将所属进程中前5个字节改为JMP   到   Myfunc
if(!dwRet)
{
DWORD   err=   GetLastError();

return     err;
}
dwRet=VirtualProtectEx(hProc,fproc,5,dwOldProtect,&dwNewProtect);//修改所属进程中的前5个字节的属性为原来的属性
if(!dwRet)
{
DWORD   err=   GetLastError();

return     err;
}

SendMessage(*hWndApp,WM_X_DEB,dwProcIDRpt,31);

return   0;
}
我用的是消息来发送调试信息,现在还有2个问题就是
        1我用WM_COPYDATA把自定义函数中截获到的文件名发送出去,但是收到的时候却总是有截断,类似 "c:\win? ", "d:\acc? "
        2.我在自定义函数中用CriticalSection来防止重入,但好像并不是完全有效果,我的程序老是有内存访问违规,让EXPLORER崩溃.
 
修改 删除 举报 引用 回复  
 

将帖子提前   放进我的网摘   推荐给好友 我要提问 帖子加分 结帖去... 管理菜单 页面风格切换标准风格老版本论坛 


--------------------------------------------------------------------------------
网站简介-广告服务-网站地图-帮助-联系方式-诚聘英才-English- 问题报告
北京创新乐知广告有限公司 版权所有 京 ICP 证 070598 号
世纪乐知(北京)网络技术有限公司 提供技术支持
Copyright © 2000-2008, CSDN.NET, All Rights Reserved
--------------------------------------------------------------------------------

 
     
 abc推荐给好友
 

        
        
        
 

 

=========================================================================================================
TRY CATCH_ALL   end_catch_ALL
setMainwind();
==================================================================
 UpdateData();
==Phrack Inc.== Volume 0x0b, Issue 0x3e, Phile #0x06 of 0x10 |=---------------=[ Kernel-mode backdoors for Windows NT ]=--------------=| |=-----------------------------------------------------------------------=| |=-----------------=[ firew0rker ]=----------------=| |=----------------=[ the nobodies ]=---------------=| --[ Table of contents 1 - PREFACE 2 - OVERVIEW OF EXISTING KERNEL-MODE BACKDOORS FOR WINDOWS NT 2.1 - NTROOTKIT 2.2 - HE4HOOK 2.3 - SLANRET (IERK, BACKDOOR-ALI) 3 - OBSCURITY ON DISK, IN REGISTRY AND IN MEMORY 4 - MY VARIANT: THORNY PATH 4.1 - SHELL 4.2 - ACTIVATION AND COMMUNICATION WITH REMOTE CLIENT 4.3 - OBSCURITY ON DISK 5 - CONCLUSION 6 - EPILOGUE 7 - LIST OF USED SOURCES 8 - FILES --[ 1 - Preface This article is intended for those who know the architecture of the Windows NT kernel and the principles of operation of NT drivers. This article examines issues involved in the development of kernel-mode tools for stealthy remote administration of Windows NT. Recently there has been a tendency of extending the use of Windows NT (2000, XP, 2003) from it's classical stronghold as home and office OS to servers. At the same time, the outdated Windows 9x family is replaced by the NT family. Because of this it should be evident that remote administration tools (backdoors) and unnoticeable access tools (rootkits) for the NT family have a certain value. Most of the published utilities work in user-mode and can thus be detected by Antivirus tools or by manual inspection. It's quite another matter those works in kernel-mode: They can hide from any user-mode program. Antivirus software will have to suplly kernel- mode components in order to detect a kernel-mode-backdoor. Software exists that protects against such backdoors (such as IPD, "Integrity Protection Driver"), but it's use is not widely spread. Kernel mode backdoors are not as widely used as they could be due to their relative complexity in comp- arison with user-mode backdoors. --[ 2 - Overview of existing Kernel-Mode backdoors for Windows NT This section briefly reviews existing kernel-mode backdoors for Windows NT. ----[ 2.1 - Ntrootkit Ntrootkit (c) by Greg Hoglund and a team of free developers [1] is a device driver for Windows NT 4.0 and 2000. It's possibilities (implemented and potential): - Receiving commands from a remote client. The rk_packet module contains a simplified IP-stack, which uses free IP-address from the subnet where the host on which Ntrootkit has been installed is situated. It's MAC and IP addresses are hardcoded in the source. Connection with the rootkit at that IP is carried out via a TCP connection to any port. The available commands in rk_command.c are: ps - list processes help - self explainatory buffertest, echo and debugint - for debugging purpose hidedir - hide directory/file hideproc - hide process(es) sniffkeys - keyboard spy There are also imcomplete pieces of code: Execute commands received via a covert channel and starting a Win32-process from a driver (a hard and complicated task). - Encrypt all traffic using Schneier's Blowfish algorithm: rk_blowfish.c is present, but not (yet ?) used - Self-defense (rk_defense.c) - hide protected objects (in this case: registry keys), identified by the string "_root_"; redirect launched processes. The hiding of processes, directories and files as implemented in rk_ioman.c is done through hooking the following functions: NtCreateFile ZwOpenFile ZwQueryDirectoryFile ZwOpenKey ZwQueryKey ZwQueryValueKey ZwEnumerateValueKey ZwEnumerateKey ZwSetValueKey ZwCreateKey The way to detect this rootkit: Make direct request to filesystem driver, send IRP to it. There is one more module that hooks file handling: rk_files.c, adopted from filemon, but it is not used. - Starting processes: An unfinished implementation of it can be found in rk_command.c, another one (which is almost complete and good) is in rk_exec.c The implementation suffers from the fact that Zw* functions which are normally unavailable to drivers directly are called through the system call interface (int 0x2E), leading to problems with different versions of the NT family as system call numbers change. It seems like the work on Ntrootkit is very loosely coordinated: every developer does what (s)he considers needed or urgent. Ntrootkit does not achieve complete (or sufficient) invisibility. It creates device named "Ntroot", visible from User-Mode. When using Ntrootkit for anything practical, one will need some means of interaction with the rootkitted system. Shortly: There will be the need for some sort of shell. Ntrootkit itself can not give out a shell directly, although it can start a process -- the downside is that the I/O of that process can not be redirected. One is thus forced to start something like netcat. It's process can be hidden, but it's TCP-connection will be visible. The missing redirection of I/O is a big drawback. However, Ntrootkit development is still in progress, and it will probably become a fully-functional tool for complete and stealthy remote administration. ----[ 2.2 - He4Hook This description is based on [2]. The filesystem access was hooked via two different methods in the versions up to and including 2.15b6. Only one of it works at one time, and in versions after 2.15b6 the first method was removed. Method A: hook kernel syscalls: =============================== ZwCreateFile, ZwOpenFile - driver version 1.12 and from 1.17 to 2.15beta6 IoCreateFile - from 1.13 to 2.15beta6 ZwQueryDirectoryFile, ZwClose - before 2.15beta6 Almost all these exported functions (Zw*) have the following function body: mov eax, NumberFunction lea edx, [esp+04h] int 2eh ; Syscall interface The "NumberFunction" is the number of the called function in the syscalls table (which itself can be accessed via the global variable KeServiceDescriptorTable). This variable points to following structure: typedef struct SystemServiceDescriptorTable { SSD SystemServiceDescriptors[4]; } SSDT, *LPSSDT; Other structures: typedef VOID *SSTAT[]; typedef unsigned char SSTPT[]; typedef SSTAT *LPSSTAT; typedef SSTPT *LPSSTPT; typedef struct SystemServiceDescriptor { LPSSTAT lpSystemServiceTableAddressTable; ULONG dwFirstServiceIndex; ULONG dwSystemServiceTableNumEntries; LPSSTPT lpSystemServiceTableParameterTable; } SSD, *LPSSD; The DescriptorTable pointed to by KeServiceDescriptorTable is only accessible from kernel mode. In User-Mode, there is something called KeServiceDescriptorTableShadow -- unfortunately it is not exported. Base services are in KeServiceDescriptorTable->SystemServiceDescriptors[0] KeServiceDescriptorTableShadow->SystemServiceDescriptors[0] KernelMode GUI services are in KeServiceDescriptorTableShadow->SystemServiceDescriptors[1] Other elements of that tables were free at moment when [2] was written, in all versions up to WinNt4(SP3-6) and Win2k build 2195. Each element of the table is a SSID structure, which contains the following data: lpSystemServiceTableAddressTable - A pointer to an array of addresses of functions that will be called if a matching syscall is called dwFirstServiceIndex - Start index for the first function dwSystemServiceTableNumEntries - Number of services in table lpSystemServiceTableParameterTable - An array of bytes specifying the number of bytes from the stack that will be passed through In order to hook a system call, He4HookInv replaces the address stored in KeServiceDescriptorTable->SystemServiceDescriptos[0].lpSystemServiceTableAddressTableIn with a pointer to it
本文来自: 乘风原创程序(http://www.qqcf.com) 详细出处参考:http://study.qqcf.com/web/530/126014.htm======================================================================================

 HOOK了ws2_32.dll的Recv怎么收不到数据?
======================================================================================
ObjectAttrubutes->ObjectName,只能获得其路径!

文件名可以这样获得:

PFILE_OBJECT pFileObject;

HANDLE FileHandle = ObjectAttrubutes->RootDirectory;

ObReferenceObjectByHandle( FileHandle, 0, NULL, KernelMode, &pFileObject, NULL );

pFileObject->FileName; //这个就是其文件名,UNICODE_STRING类型

与ObjectAttrubutes->ObjectName 相加就是全路径

===============================================================
#include "winsock2.h"   
#pragma comment(lib, “wsock32.lib”)BYTE JMPsend[5] = {0xe9};   
BYTE byteJmpSend[10] = {0x8B, 0xFF, 0x55, 0x8B, 0xEC, 0xE9, 0x0, 0x0, 0x0, 0x0};   
  
BYTE JMPrecv[5] = {0xe9};   
BYTE byteJmpRecv[10] = {0x8B, 0xFF, 0x55, 0x8B, 0xEC, 0xE9, 0x0, 0x0, 0x0, 0x0};   
  
int WINAPI MyRecv(SOCKET s, char FAR * buf, int len, int flags)   
{   
    int rets = 0;   
    _asm   
    {   
        push flags   
        push len   
    push buf   
    push s   
    lea eax, byteJmpRecv   
    call eax   
    mov dword ptr [rets], eax   
    }   
    return rets;   
}   
  
int WINAPI MySend(SOCKET s, char FAR * buf, int len, int flags)   
{   
    int rets = 0;   
    _asm   
    {   
    push flags   
    push len   
    push buf   
    push s   
    lea eax, byteJmpSend   
    call eax   
    mov dword ptr [rets], eax   
    }   
    return rets;   
}   
  
BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved )   
{   
    switch (ul_reason_for_call)   
    {   
    case DLL_PROCESS_ATTACH:   
    {   
        DWORD dwOld;   
  
        DWORD *pdw = (DWORD *)(JMPsend+1);   
        *pdw = DWORD((ULONG)MySend - (ULONG)send - 5);   
        VirtualProtect(send, 5, PAGE_READWRITE, &dwOld);   
        WriteProcessMemory(GetCurrentProcess() , send, JMPsend, 5, &dwOld);   
        VirtualProtect(send, 5, dwOld, NULL);   
        *((DWORD *)(byteJmpSend+6)) = ((DWORD)send+5) - ((DWORD)byteJmpSend+10);   
  
        pdw = (DWORD *)(JMPrecv+1);   
        *pdw = DWORD((ULONG)MyRecv - (ULONG)recv - 5);   
        VirtualProtect(recv, 5, PAGE_READWRITE, &dwOld);   
        WriteProcessMemory(GetCurrentProcess(), recv, JMPrecv, 5, &dwOld);   
        VirtualProtect(recv, 5, dwOld, NULL);   
        *((DWORD *)(byteJmpRecv+6)) = ((DWORD)recv+5) - ((DWORD)byteJmpRecv+10);   
  
        break;   
    }   
    case DLL_THREAD_ATTACH:   
        break;   
    case DLL_THREAD_DETACH:   
        break;   
    case DLL_PROCESS_DETACH:   
        break;   
    }   
    return TRUE;   
}  
==============================================================================================================
我HOOK了传奇3客户端的ws2_32.dll的Recv收不到任何数据。而HOOK了wsock32.dll的recv只能得到一部分数据,不完整。我已脱壳,反汇编了客户端,里面没用到wsock32.dll文件。怎么HOOK了wsock32.dll的recv有数据呢?
Send部分一直有数据。已换多台机器试过,望高手解答。
下面贴我的代码

unit APIHook;

interface

uses
  SysUtils,BaseUnit,
  Windows, WinSock,inifiles;

type
  //要HOOK的API函数定义
  TSockProc = function (s: TSocket; var Buf; len, flags: Integer): Integer; stdcall;

  PJmpCode = ^TJmpCode;
  TJmpCode = packed record
    JmpCode: BYTE;
    Address: TSockProc;
    MovEAX: Array [0..2] of BYTE;
  end;

  //--------------------函数声明---------------------------
  procedure HookAPI;
  procedure UnHookAPI;

var
  OldSend, OldRecv: TSockProc;      //原来的API地址
  JmpCode: TJmpCode;
  OldProc: array [0..1] of TJmpCode;
  AddSend, AddRecv: pointer;        //API地址
  TmpJmp: TJmpCode;
  ProcessHandle: THandle;

  logF : Textfile; //日志文件
  LayTime:integer;    //延迟时间,单位毫秒
  Configfile:TInifile;  //配置文件
implementation

{---------------------------------------}
{函数功能:Send函数的HOOK
{函数参数:同Send
{函数返回值:integer
{---------------------------------------}
function MySend(s: TSocket; var Buf; len, flags: Integer): Integer; stdcall;
var
  dwSize: cardinal;
  BufTemp:array [0..65535] of char;
  ReceiveStr:string;
begin
  copymemory(@BufTemp,@buf,len);
  //08 00 A1 0F 77 00 00 09
  //if(ord(o[0])=8)and(ord(o[1])=0)and(ord(o[2])=161)and(ord(o[3])=15)Then
  //if LockedSpeed Then o[7] := Char(iLockedSpeed);
  //copymemory(@buf,@o,len);

  //调用直正的Send函数
  WriteProcessMemory(ProcessHandle, AddSend, @OldProc[0], 8, dwSize);
  Result := OldSend(S, Buf, len, flags);
  JmpCode.Address := @MySend;
  WriteProcessMemory(ProcessHandle, AddSend, @JmpCode, 8, dwSize);

  //日志
  Writeln(logF,DateTimeToSTr(Now)+' '+'发送:'+Format('状态:%d',[status])); //写入日志文件
  Writeln(logF,DateTimeToSTr(Now)+' '+'总发送ASCII:'+StrToASCII(BufTemp,0)); //写入日志文件
  Writeln(logF,DateTimeToSTr(Now)+' '+'总发送密文字符:'+BufTemp); //写入日志文件
  ReceiveStr:=Decode(BufTemp);  //获取接收的回答完毕字符串,进行
  Writeln(logF,DateTimeToSTr(Now)+' '+'发送解密:'+ReceiveStr); //写入日志文件
end;

{---------------------------------------}
{函数功能:Recv函数的HOOK
{函数参数:同Recv
{函数返回值:integer
{---------------------------------------}
function MyRecv(s: TSocket; var Buf; len, flags: Integer): Integer; stdcall;
var
  dwSize: cardinal;
  BufTemp:array [0..$270F] of char;
  ReceiveStr:string;
  point:tpoint;
  high:integer;
begin
  try
  copymemory(@BufTemp,@buf,len);
 
  //调用直正的Recv函数
  WriteProcessMemory(ProcessHandle, AddRecv, @OldProc[1], 8, dwSize);
  Result := OldRecv(S, Buf, len, flags);
  JmpCode.Address := @MyRecv;
  WriteProcessMemory(ProcessHandle, AddRecv, @JmpCode, 8, dwSize);

  //日志
  Writeln(logF,DateTimeToSTr(Now)+' '+'总接收状态:'+Format('状态:%d',[status])); //写入日志文件
  Writeln(logF,DateTimeToSTr(Now)+' '+'总接收ASCII:'+StrToASCII(BufTemp,0)); //写入日志文件
  Writeln(logF,DateTimeToSTr(Now)+' '+'总接收密文字符:'+BufTemp); //写入日志文件
  ReceiveStr:=Decode(BufTemp);  //获取接收的回答完毕字符串,进行
  Writeln(logF,DateTimeToSTr(Now)+' '+'接收解密:'+ReceiveStr); //写入日志文件
end;

{------------------------------------}
{过程功能:HookAPI
{过程参数:无
{------------------------------------}
procedure HookAPI;
var
  DLLModule: THandle;
  dwSize: cardinal;
  hProc:Thandle;
  dwIdOld,dwIdNew:Dword;

  //用来存储入口变量
  m_OldFunc:array [0..7] of BYTE;
  m_NewFunc:array [0..7] of BYTE;
  pNewFuncAddress:^DWORD; //地址指针
  i:integer;
begin
  ProcessHandle := GetCurrentProcess;
  //DLLModule := LoadLibrary('wsock32.dll'); //"ws2_32.dll"/*wsock32.dll*/
  DLLModule := LoadLibrary('ws2_32.dll');  //WSA系列函数在wsock32.dll找不到??

  AddSend := GetProcAddress(DLLModule, 'send');  //取得API地址
  //AddRecv := GetProcAddress(DLLModule, 'recv');


  JmpCode.JmpCode := $B8;
  JmpCode.MovEAX[0] := $FF;
  JmpCode.MovEAX[1] := $E0;
  JmpCode.MovEAX[2] := 0;

  dwIdOld:=GetCurrentProcessId;
  hProc:=OpenProcess(PROCESS_ALL_ACCESS,false,dwIdOld);
  VirtualProtectEx(hProc,AddSend,8,PAGE_READWRITE,@dwIdOld);//修改所属进程中send的前5个字节的属性为可写
  ReadProcessMemory(ProcessHandle, AddSend, @OldProc[0], 8, dwSize);
  JmpCode.Address := @MySend;
  WriteProcessMemory(ProcessHandle, AddSend, @JmpCode, 8, dwSize);   //修改Send入口
  VirtualProtectEx(hProc,AddSend,8,dwIdOld,@dwIdOld); //修改所属进程中send的前5个字节的属性为原来的属性

  JmpCode.Address:=TSockProc($00400000);
  //DLLModule := LoadLibrary('wsock32.dll');  //WSA系列函数在wsock32.dll找不到??
  DLLModule := LoadLibrary('ws2_32.dll');
  AddRecv := GetProcAddress(DLLModule, 'recv');
  VirtualProtectEx(hProc,AddRecv,8,PAGE_READWRITE,@dwIdOld);//修改所属进程中send的前5个字节的属性为可写

  ReadProcessMemory(GetCurrentProcess, AddRecv, @OldProc[1], 8, dwSize);
  JmpCode.Address := @MyRecv;
  WriteProcessMemory(ProcessHandle, AddRecv, @JmpCode, 8, dwSize);   //修改Recv入口

{  ReadProcessMemory(ProcessHandle,AddRecv,@OldProc[1],5,dwSize);
  m_NewFunc[0]:=$e9;
  pNewFuncAddress:=@m_NewFunc[1];
  pNewFuncAddress^:=DWORD(@MySend)-DWORD(AddRecv)-5;        }

  VirtualProtectEx(hProc,AddRecv,8,dwIdOld,@dwIdOld); //修改所属进程中send的前5个字节的属性为原来的属性

  OldSend := AddSend;
  OldRecv := AddRecv;

  //写入日志,用于调试
  AssignFile(logF,'c:\ek.txt'); //让变量F和C:\ek.txt关连
  ReWrite(logF); //Create a new file named ek.txt
  Writeln(logF,'开始hookAPI'); //写入文件
  Writeln(logF,Format('%X:%X',[integer(AddSend),integer(@MySend)])); //写入文件
  Writeln(logF,Format('%X:%X',[integer(AddRecv),integer(@MyRecv)])); //写入文件

end;

{------------------------------------}
{过程功能:取消HOOKAPI
{过程参数:无
{------------------------------------}
procedure UnHookAPI;
var
  dwSize: Cardinal;
begin
  Writeln(logF,Format('关闭%X:%X',[integer(@OldProc[0]),integer(@OldProc[1])])); //写入文件
  WriteProcessMemory(ProcessHandle, AddSend, @OldProc[0], 8, dwSize);
  WriteProcessMemory(ProcessHandle, AddRecv, @OldProc[1], 8, dwSize);
  //Closefile(logF);    //关闭日志
end;

end.


 

评论(?)
阅读(?)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
网易公司版权所有 ©1997-2009