GaRY's Blog

Beginning is always beautiful

Ring3 Inline Hook Demo

第一次写这种内存补丁一样的东西.开始怎么写都出错.字节码没有对齐..跳转地址算错.等等...后来用ida分析+od调试搞定.(头一次认认真真用od和ida...值得纪念)
测试环境xp sp2+vc6.0

#include <stdio.h>
#include 
<windows.h>

// 保存原始的5个字节代码,注意一定要保证完整
BYTE orig_code[5= {0x900x900x900x900x90};
// JMP 0xXXXXXXXX
BYTE hook_code[5= 0xe90000 };
BYTE jmp_orig_code[
5= 0xe90000};

int func();
int fake_func();
void hook_func();
int jmp_back();


int main(int argc, char **argv)
{
    
int ret;
    hook_func();
    ret 
= func();
    
return ret;
}


int func()
{
    printf(
"I'm func(),I'm called!\r\n");
    
return 0;
}


void hook_func()
{
    DWORD dwOldProtect;
    
if(!VirtualProtect(func, 5, PAGE_EXECUTE_READWRITE, &dwOldProtect))
    
{
        printf(
"VirtualProtect error!\r\n");
        
return;
    }

    
if(!VirtualProtect(jmp_back, 12, PAGE_EXECUTE_READWRITE, &dwOldProtect))
    
{
        printf(
"VirtualProtect error!\r\n");
        
return;
    }


    
// 保存原始操作码
    memcpy(orig_code, (BYTE *)func, 5);
    
// 计算fack_func地址
    *((ULONG*)(hook_code+1) ) = (ULONG)fake_func - (ULONG)func - 5;
    
// 修改原始入口
    memcpy((BYTE *)func, hook_code, 5);
    
// 计算跳回地址
    *( (ULONG*)(jmp_orig_code+1) ) = (ULONG)func - (ULONG)jmp_back -5;
    
// 填充jmp_back
    memcpy((BYTE *)jmp_back, orig_code, 5);    
    memcpy((BYTE 
*)jmp_back+5, jmp_orig_code, 5);
}


__declspec(naked) 
int jmp_back()
{
    __asm
    
{
        _emit 
0x90
        _emit 
0x90
        _emit 
0x90
        _emit 
0x90
        _emit 
0x90
        _emit 
0x90
        _emit 
0x90
        _emit 
0x90
        _emit 
0x90
        _emit 
0x90
    }

}


int fake_func()
{
    
int ret;
    printf(
"I'm fake_func(),I'm called!\r\n");
    ret 
= jmp_back();
    
return ret;
}


测试结果:

 

参考: http://www.whitecell.org/forums/viewthread.php?tid=360

posted on 2007-05-29 13:45 wofeiwo 阅读(2617) 评论(2)  编辑 收藏 引用 网摘 所属分类: TipsOthers

评论

# re: Ring3 Inline Hook Demo 2008-03-11 12:28 exportwrc

测了一下,5字节有问题,指令被截断了,无法返回到func函数,改为8字节就可以  回复  更多评论   

# re: Ring3 Inline Hook Demo 2008-03-18 18:04 GaRY

@exportwrc
呵呵.推荐用LDE,指令截断问题就不用再考虑了  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航:

导航

<2008年3月>
2425262728291
2345678
9101112131415
16171819202122
23242526272829
303112345

统计

留言簿(10)

随笔分类(90)

随笔档案(61)

搜索

最新随笔

最新评论