在内存中读取函数的ShellCode并执行

来源:互联网 发布:mysql存储过程实例 编辑:程序博客网 时间:2024/06/06 04:20

在内存中读取函数的ShellCode并执行

下面是一个例子,实现的效果是将fun1函数的十六进制读取出来,在内存中将str1的地址改成str2,分配一块内存,将改好的函数的ShellCode写入并执行。

[cpp] view plain copy
  1. // FunTest.cpp : 定义控制台应用程序的入口点。  
  2. //  
  3. //  
  4. #include "stdafx.h"  
  5. #include <windows.h>  
  6.   
  7. #pragma comment(lib,"user32.lib")  
  8.   
  9. char *str1 = "aaaa";  //字符串指针1  
  10. char *str2 = "bbbb";  //字符串指针2  
  11.   
  12. void fun1()  
  13. {  
  14.     MessageBox(0,str1,0,0);  
  15. }  
  16.   
  17. void fun2()  
  18. {  
  19.     MessageBox(0,"2",0,0);  
  20. }  
  21.   
  22.   
  23. int _tmain(int argc, _TCHAR* argv[])  
  24. {  
  25.   
  26.     fun1();  //调用fun1函数测试一下  
  27.   
  28.     //获取fun1函数的大小  
  29.     int iFun1Size = ((DWORD)fun2) - ((DWORD)fun1);  
  30.     printf("fun1 size: %d\n",iFun1Size);  
  31.   
  32.     //获取fun1函数的十六进制内容  
  33.     BYTE *pFun1Body = new BYTE [iFun1Size];  
  34.     memcpy(pFun1Body,&fun1,iFun1Size);  
  35.     for (int i=0;i<=iFun1Size;i++)  
  36.     {  
  37.         printf("%x",*(pFun1Body+i));  
  38.     }  
  39.     printf("\n");  
  40.       
  41.   
  42.     //打印字符指针地址  
  43.     DWORD dwstrAddress1 = (DWORD)&str1;  
  44.     DWORD dwstrAddress2 = (DWORD)&str2;  
  45.     printf("Address1 %x\n",dwstrAddress1);  
  46.     printf("Address2 %x\n",dwstrAddress2);  
  47.   
  48.     //判断  
  49.     for (int i=0;i<(iFun1Size-4);i++)  
  50.     {  
  51.         DWORD *dwPtr = (DWORD *)((BYTE *)pFun1Body + i);  
  52.           
  53.         //找str1的地址  
  54.         if (*dwPtr == dwstrAddress1)   
  55.         {  
  56.             *dwPtr = (DWORD)dwstrAddress2;  //替换字符串指针地址  
  57.             printf("dwstrAddress1 found\n");  
  58.         }  
  59.         else if (*dwPtr == dwstrAddress2)  
  60.         {  
  61.             printf("dwstrAddress2 found\n");  
  62.         }  
  63.   
  64.     }  
  65.       
  66.     //分配内存  
  67.     PVOID pData = VirtualAlloc(NULL,iFun1Size,MEM_COMMIT,PAGE_EXECUTE_READWRITE);  
  68.     if(!pData)  
  69.     {  
  70.         DWORD dwError = GetLastError();  
  71.         printf("VirtualAllocEx error %d \n",dwError);  
  72.         return 0;  
  73.     }  
  74.   
  75.   
  76.     //写内存  
  77.     HANDLE h = OpenProcess(PROCESS_ALL_ACCESS,0,GetCurrentProcessId());  
  78.     if(!WriteProcessMemory(h,pData,pFun1Body,iFun1Size,0))  
  79.     {  
  80.         DWORD dwError = GetLastError();  
  81.         printf("WriteProcessMemory error %d\n",dwError);  
  82.         return 0;  
  83.     }  
  84.       
  85.     //执行  
  86.     _asm  
  87.     {  
  88.         mov eax,pData;  
  89.         call eax  
  90.     }  
  91.   
  92.     //释放内存  
  93.     VirtualFree(pData,0,MEM_RELEASE);  
  94.     delete []pFun1Body;  
  95.   
  96.     getchar();  
  97.     return 0;  
  98. }  

原创粉丝点击