BehaviorMonView.cpp
上传用户:xuemeng126
上传日期:2022-07-05
资源大小:454k
文件大小:23k
源码类别:

系统编程

开发平台:

Visual C++

  1. // BehaviorMonView.cpp : implementation of the CBehaviorMonView class
  2. //
  3. #include "stdafx.h"
  4. #include "BehaviorMon.h"
  5. #include "BehaviorMonDoc.h"
  6. #include "BehaviorMonView.h"
  7. #include "IoctlCmd.h" 
  8. #include <tchar.h>
  9. #include <commctrl.h>  
  10. #include <stdio.h>
  11. #include <string.h>
  12. #include <winioctl.h>
  13. #ifdef _DEBUG
  14. #define new DEBUG_NEW
  15. #undef THIS_FILE
  16. static char THIS_FILE[] = __FILE__;
  17. #endif
  18. //宏定义 
  19. // Number of columns in the listview
  20. #define NUMCOLUMNS 7
  21. // maximum length of an entier listview line
  22. #define MAXITEMLENGTH 0x1000
  23. //静态变量,可以在线程中使用
  24. static CSortListCtrl m_list_behavior;
  25. static CImageList images;
  26. static CString m_row_num;
  27. static HICON hIcon;
  28. static long num=0;
  29. static char num_s[32];
  30. static SYSTEMTIME local_time;
  31. static char processname[16];
  32. static char processfullname[512];
  33. static char nativeAPIname[64];
  34. static char behavior[1024];
  35. static char result[64];
  36. static DWORD b=0;
  37. //保存被hook的nativeAPI函数信息
  38. typedef struct {
  39. const char * nativeAPIname;//函数名称
  40. //ULONG Index;//在描述符表中的代号
  41. //ULONG RealCallee;//真正的地址
  42. //ULONG proxyfunadd;//代理函数地址
  43. //BOOL  hooked;
  44. }HOOKED_API_INFO;
  45. static HOOKED_API_INFO hook_API_info[100];
  46. static int hook_num=0;
  47. //交互缓冲区,驱动往里写,前台往出读,做显示
  48. typedef struct{
  49. char IsRead;
  50. char ProcessName[32];
  51. char NativeAPIName[32];
  52. char ProcessFullName[512];
  53. char Behavior[1024];
  54. char Result[64];
  55. char Time[16];
  56. }LOG_BEHAVIOR;
  57. static LOG_BEHAVIOR log_behavior[10];
  58. static int curr_read_pointer=0;
  59. static int LOG_BEHAVIOR_NUM=10;
  60. /////////////////////////////////////////////////////////////////////////////
  61. static HINSTANCE hInst; // current instance 当前实例
  62. static HANDLE device;
  63. static char outputbuff[2048]; 
  64. static char processnamebuff[2048];
  65. static char * strings[256]; 
  66. static DWORD stringcount; 
  67. static HANDLE hThread;
  68. static BOOL IsSetup;
  69. static BOOLEAN Capture = FALSE;
  70. static DWORD startTime;
  71. // Buffer into which driver can copy statistics
  72. char Stats[ LOGBUFSIZE ];
  73. // Current fraction of buffer filled
  74. DWORD StatsLen;
  75. static BOOLEAN ClockTime = TRUE;
  76. static BOOLEAN IsNT= TRUE;
  77. // General buffer for storing temporary strings
  78. static TCHAR msgbuf[ MAXITEMLENGTH ];
  79. // performance counter frequency
  80. LARGE_INTEGER PerfFrequency;
  81. // CBehaviorMonView
  82. IMPLEMENT_DYNCREATE(CBehaviorMonView, CFormView)
  83. BEGIN_MESSAGE_MAP(CBehaviorMonView, CFormView)
  84. //{{AFX_MSG_MAP(CBehaviorMonView)
  85. ON_WM_CLOSE()
  86. ON_WM_SIZE()
  87. ON_NOTIFY(NM_CLICK, IDC_LIST_BEHAVIOR, OnClickListBehavior)
  88. ON_WM_TIMER()
  89. ON_BN_CLICKED(IDC_BUTTON_HOOK, OnButtonHook)
  90. ON_BN_CLICKED(IDC_BUTTON_UNHOOK, OnButtonUnhook)
  91. ON_WM_CREATE()
  92. //}}AFX_MSG_MAP
  93. // Standard printing commands
  94. ON_COMMAND(ID_FILE_PRINT, CFormView::OnFilePrint)
  95. ON_COMMAND(ID_FILE_PRINT_DIRECT, CFormView::OnFilePrint)
  96. ON_COMMAND(ID_FILE_PRINT_PREVIEW, CFormView::OnFilePrintPreview)
  97. END_MESSAGE_MAP()
  98. /////////////////////////////////////////////////////////////////////////////
  99. // CBehaviorMonView construction/destruction
  100. CBehaviorMonView::CBehaviorMonView()
  101. : CFormView(CBehaviorMonView::IDD)
  102. {
  103. //{{AFX_DATA_INIT(CBehaviorMonView)
  104. m_row_num = _T("");
  105. //}}AFX_DATA_INIT
  106. // TODO: add construction code here
  107. setup(); 
  108. IsSetup=TRUE;
  109. }
  110. CBehaviorMonView::~CBehaviorMonView()
  111. {
  112. cleanup();
  113. }
  114. void CBehaviorMonView::DoDataExchange(CDataExchange* pDX)
  115. {
  116. CFormView::DoDataExchange(pDX);
  117. //{{AFX_DATA_MAP(CBehaviorMonView)
  118. DDX_Control(pDX, IDC_LIST_BEHAVIOR, m_list_behavior);
  119. DDX_Text(pDX, IDC_STATIC_ROW, m_row_num);
  120. //}}AFX_DATA_MAP
  121. }
  122. BOOL CBehaviorMonView::PreCreateWindow(CREATESTRUCT& cs)
  123. {
  124. // TODO: Modify the Window class or styles here by modifying
  125. //  the CREATESTRUCT cs
  126. return CFormView::PreCreateWindow(cs);
  127. }
  128. void CBehaviorMonView::OnInitialUpdate()
  129. {
  130. CFormView::OnInitialUpdate();
  131. GetParentFrame()->RecalcLayout();
  132. ResizeParentToFit();
  133. m_list_behavior.SetHeadings( _T("#,40;Time,90;Process Name,200;Native API,100;Behavior,500;Result,60") ); ///设置列头信息
  134. m_list_behavior.LoadColumnInfo();                              ///加载列信息
  135. //CListCtrl扩展样式改变
  136. DWORD dwStyle;
  137. dwStyle = m_list_behavior.GetStyle();  //取得样式
  138. dwStyle |=  LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT | LVS_EX_HEADERDRAGDROP ;   //添加样式
  139. m_list_behavior.SetExtendedStyle(dwStyle);     //重新设置
  140. /*
  141. m_list_behavior.SetExtendedStyle( 
  142. //LVS_EX_ONECLICKACTIVATE //单击选中项 
  143. | LVS_EX_FULLROWSELECT // 答应整行选中 
  144. | LVS_EX_HEADERDRAGDROP // 答应标题拖拽 
  145. | LVS_SHOWSELALWAYS //高亮度显示被选中项 
  146. | LVS_EX_GRIDLINES //网格线 
  147. | LVS_EX_FLATSB // 扁平风格滚动 
  148. );  */  
  149. images.Create(16,16,ILC_COLOR32 ,10,10);
  150. m_list_behavior.SetImageList(&images,LVSIL_SMALL);
  151. //for test
  152. /*
  153. hIcon=AfxGetApp()->LoadIcon(IDI_ICON_DEFAULT);
  154. int j=images.Add(hIcon);
  155. GetLocalTime(&local_time);
  156. ltoa(num,num_s,10);
  157. CString strTime;   
  158. strTime.Format(_T("%.2d:%.2d:%.2d.%.3d"),local_time.wHour,local_time.wMinute,local_time.wSecond,local_time.wMilliseconds);  
  159. m_list_behavior.AddItem(j,num_s,strTime, _T("是"),_T("是"),_T("是"),_T("是"));///添加表项
  160. num++;
  161. */
  162. CWnd   *pButton_Unhook   =   this->GetDlgItem(IDC_BUTTON_UNHOOK); 
  163. pButton_Unhook->EnableWindow(FALSE);
  164. }
  165. /////////////////////////////////////////////////////////////////////////////
  166. // CBehaviorMonView printing
  167. BOOL CBehaviorMonView::OnPreparePrinting(CPrintInfo* pInfo)
  168. {
  169. // default preparation
  170. return DoPreparePrinting(pInfo);
  171. }
  172. void CBehaviorMonView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
  173. {
  174. // TODO: add extra initialization before printing
  175. }
  176. void CBehaviorMonView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
  177. {
  178. // TODO: add cleanup after printing
  179. }
  180. void CBehaviorMonView::OnPrint(CDC* pDC, CPrintInfo* /*pInfo*/)
  181. {
  182. // TODO: add customized printing code here
  183. //*********************************************************************************
  184. void CBehaviorMonView::clear_list()
  185. {
  186. m_list_behavior.DeleteAllItems();
  187. num=0;
  188. char row_num[10];
  189. itoa(num,row_num,10); 
  190. strcat(row_num,"个行为");
  191. m_list_behavior.GetParent()->SetDlgItemText(IDC_STATIC_ROW,row_num);
  192. }
  193. /******************************************************************************
  194. *
  195. * FUNCTION: Split
  196. *
  197. * PURPOSE: Split a delimited line into components
  198. *
  199. ******************************************************************************/
  200. int Split( char * line, char delimiter, char * items[] )
  201. {
  202. int cnt = 0;
  203. for (;;)  {
  204. // Add prefix to list of components
  205. items[cnt++] = line;
  206. // Check for more components
  207. line = strchr( line, delimiter );
  208. if ( line == NULL )
  209. return cnt;
  210. // Terminate previous component and move to next
  211. *line++ = '';
  212. }
  213. }
  214. void displayError(char * s)
  215. {
  216.     LPVOID lpMsgBuf; 
  217.     FormatMessage( 
  218. FORMAT_MESSAGE_ALLOCATE_BUFFER | 
  219. FORMAT_MESSAGE_FROM_SYSTEM | 
  220. FORMAT_MESSAGE_IGNORE_INSERTS, 
  221. NULL, 
  222. GetLastError(), 
  223. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language 
  224. (LPTSTR) &lpMsgBuf, 
  225. 0, 
  226. NULL 
  227. ); 
  228.     // Process any inserts in lpMsgBuf. 
  229.     // ... 
  230.     // Display the string. 
  231. CString cs=CString(s)+" "+(LPCTSTR)lpMsgBuf;
  232.     AfxMessageBox(cs);
  233.     // Free the buffer. 
  234.     LocalFree( lpMsgBuf ); 
  235. }
  236. //安装设备驱动
  237. //安装了设备驱动后,设备驱动程序中负责创建一个新的虚拟设备
  238. void CBehaviorMonView::setup()
  239. {
  240. char namebuff[256]; 
  241. //get path to ths .sys.file
  242. GetModuleFileName(0,namebuff,256);
  243. DWORD  a=strlen(namebuff);
  244. while(1)
  245. {
  246. if(namebuff[a]=='\')break;
  247. a--;
  248. }
  249. a++;
  250. strcpy(&namebuff[a], "BehaviorMon.sys");
  251. /*
  252. 安装驱动程序流程:
  253. 1,调用OpenSCManager()打开服务控制管理器
  254. 2,调用CreateService()创建一个服务,服务类型为内核驱动
  255. 3,调用OpenService()取得服务句柄,启动服务
  256. 4,调用StartService()启动服务,停止服务
  257. 4,调用ControlService()停止服务,删除服务
  258. 4,调用DeleteService()删除服务
  259. 5,调用CloseServiceHandle()关闭服务句柄
  260. */
  261. //create service
  262. //system("msiexec /unregserver");
  263. SC_HANDLE t;SERVICE_STATUS stat;
  264. SC_HANDLE man=OpenSCManager(0,0,SC_MANAGER_ALL_ACCESS);
  265. t=OpenService(man,"behaviormonservice",SERVICE_ALL_ACCESS);
  266. ControlService(t,SERVICE_CONTROL_STOP,&stat);
  267. DeleteService(t);
  268. CloseServiceHandle(t);
  269. if(man==NULL)
  270. {
  271. displayError("打开服务管理器失败!");
  272. }
  273. t=CreateService(man,"behaviormonservice","behaviormonservice",
  274. SERVICE_START|SERVICE_STOP,SERVICE_KERNEL_DRIVER,SERVICE_DEMAND_START,SERVICE_ERROR_NORMAL,namebuff,0,0,0,0,0);
  275. if(t==NULL)
  276. {
  277. displayError("创建服务失败!");
  278. if(0==StartService(t,0,0))
  279. {
  280. displayError("启动服务失败!");
  281.     }    
  282. }
  283. //*********************************************************************************
  284. void CBehaviorMonView::cleanup()
  285. //结束线程hThread
  286. //TerminateThread(hThread,0);
  287. Capture=FALSE;
  288. Sleep(1500);
  289. unhook();
  290. SC_HANDLE man;
  291. if((man=OpenSCManager(0,0,SC_MANAGER_ALL_ACCESS))==NULL)
  292.     {
  293. displayError("打开服务管理器失败!");
  294.     }
  295. SERVICE_STATUS stat;
  296. SC_HANDLE t;
  297. if((t=OpenService(man,"behaviormonservice",SERVICE_ALL_ACCESS))==NULL)
  298.     {
  299. displayError("打开服务失败!");
  300.     }
  301. if(ControlService(t,SERVICE_CONTROL_STOP,&stat)==0)
  302.     {
  303. displayError("控制服务失败!");
  304.     } 
  305.     if (! DeleteService(t) ) 
  306.     {
  307. displayError("设备驱动卸载失败!");
  308.     }  
  309. if(!CloseServiceHandle(t))
  310. {
  311. displayError("关闭服务句柄失败!");
  312.     } 
  313. IsSetup=FALSE;
  314. }
  315. //*********************************************************************************
  316. //线程函数
  317. //*********************************************************************************
  318. static void threadfun()
  319. {  
  320. int j; 
  321. char name[1024];
  322. char row_num[20];
  323. while(1)
  324. {  
  325. while(log_behavior[curr_read_pointer].IsRead=='y')
  326. {
  327. Sleep(100);
  328. continue;
  329. }  
  330. //得到程序名+完整路径
  331. strcpy(name,log_behavior[curr_read_pointer].ProcessName); 
  332. strcat(name,"(");
  333. //进程的完整路径,用这个路径可以得到图标
  334. strcat(name,log_behavior[curr_read_pointer].ProcessFullName);
  335. strcat(name,")");
  336. //得到进程图标
  337. hIcon=ExtractIcon(AfxGetInstanceHandle(),log_behavior[curr_read_pointer].ProcessFullName,0);
  338. if(hIcon!=NULL)   
  339. j=images.Add(hIcon); 
  340. else
  341. {
  342. hIcon=AfxGetApp()->LoadIcon(IDI_ICON_DEFAULT);
  343. j=images.Add(hIcon);
  344. //得到序号
  345. ltoa(num,num_s,10);
  346. //加入列表中
  347. m_list_behavior.AddItem(
  348. j,//图标号
  349. num_s,//序号#
  350. _T(log_behavior[curr_read_pointer].Time),// time
  351. //_T("time"),
  352. _T(name),//processname:pid
  353. _T(log_behavior[curr_read_pointer].NativeAPIName),//NativeAPIname
  354. _T(log_behavior[curr_read_pointer].Behavior),//Behavior
  355. //_T("behavior"),
  356. _T("允许"));//result
  357. num++;
  358. //读取完成
  359. log_behavior[curr_read_pointer].IsRead='y';
  360. curr_read_pointer++;
  361. if(curr_read_pointer==LOG_BEHAVIOR_NUM)
  362. curr_read_pointer=0;
  363. //显示目前提取了多少个行为 
  364. itoa(num,row_num,10); 
  365. strcat(row_num,"个行为");
  366. m_list_behavior.GetParent()->SetDlgItemText(IDC_STATIC_ROW,row_num);
  367. }
  368. }
  369. //让驱动hook SSDT中指定的Native API
  370. void CBehaviorMonView::hook()
  371. int i; 
  372. hook_num=0;
  373. hook_API_info[hook_num++].nativeAPIname="NtRestoreKey";
  374. hook_API_info[hook_num++].nativeAPIname="NtOpenKey";
  375. hook_API_info[hook_num++].nativeAPIname="NtCreateKey";
  376. hook_API_info[hook_num++].nativeAPIname="NtQueryValueKey";
  377. hook_API_info[hook_num++].nativeAPIname="NtQueryKey";
  378. hook_API_info[hook_num++].nativeAPIname="NtDeleteKey";
  379. hook_API_info[hook_num++].nativeAPIname="NtDeleteValueKey";
  380. hook_API_info[hook_num++].nativeAPIname="NtSetValueKey";
  381. hook_API_info[hook_num++].nativeAPIname="NtEnumerateKey";
  382. hook_API_info[hook_num++].nativeAPIname="NtEnumerateValueKey";
  383. hook_API_info[hook_num++].nativeAPIname="NtOpenFile";
  384. hook_API_info[hook_num++].nativeAPIname="NtWriteFile";
  385. hook_API_info[hook_num++].nativeAPIname="NtCreateFile";
  386. hook_API_info[hook_num++].nativeAPIname="NtCreateProcess";
  387. hook_API_info[hook_num++].nativeAPIname="NtCreateProcessEx";
  388. hook_API_info[hook_num++].nativeAPIname="NtCreateSection";
  389. hook_API_info[hook_num++].nativeAPIname="NtOpenThread";
  390. hook_API_info[hook_num++].nativeAPIname="NtCreateThread";
  391. hook_API_info[hook_num++].nativeAPIname="NtOpenProcess";
  392. hook_API_info[hook_num++].nativeAPIname="NtOpenSection";
  393. hook_API_info[hook_num++].nativeAPIname="NtCreateSymbolicLinkObject";
  394. hook_API_info[hook_num++].nativeAPIname="NtSetSystemTime";
  395. //安装设备驱动
  396. //setup();
  397. //MessageBox("设备驱动安装成功!","提示",MB_OK);
  398. DWORD controlbuff[2048];
  399. DWORD dw;
  400.  
  401. //打开设备
  402. if(!device)
  403. device=CreateFile("\\.\BEHAVIORMON",GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_SYSTEM,0);
  404. // Have driver zero information
  405. if ( ! DeviceIoControl( device, IOCTL_BEHAVIORMON_ZEROSTATS,NULL, 0, NULL, 0, &dw, NULL ) ) 
  406. {
  407. return;
  408. }
  409. //告诉后台驱动hook上面的函数
  410. char * pcontrolbuff=(char *)controlbuff;
  411. int offsetcontrolbuff=0;
  412. //填写交换缓冲区的地址
  413. controlbuff[0]=(DWORD)&log_behavior[0];
  414. offsetcontrolbuff+=4;
  415. //填写LOG_BEHAVIOR数组的大小 
  416. controlbuff[1]=LOG_BEHAVIOR_NUM;
  417. offsetcontrolbuff+=4;
  418. //被Hook的NativeAPI的总个数
  419. controlbuff[2]=hook_num;
  420. offsetcontrolbuff+=4;
  421. //把前面要Hook的Native API函数的基本信息(name,index)写入controlbuff
  422. for(i=0;i<hook_num;i++)
  423. {
  424. DWORD * addr=(DWORD *)(1+(DWORD)GetProcAddress(GetModuleHandle("ntdll.dll"),hook_API_info[i].nativeAPIname));
  425. //被Hook的NativeAPI的名称
  426. strcpy(pcontrolbuff+offsetcontrolbuff,hook_API_info[i].nativeAPIname);
  427. offsetcontrolbuff+=strlen(hook_API_info[i].nativeAPIname);
  428. offsetcontrolbuff+=1;
  429. //被Hook的NativeAPI的Index
  430. //controlbuff[2]=addr[0];//函数调用地址的地址
  431. memmove(pcontrolbuff+offsetcontrolbuff,&addr[0],4);
  432. offsetcontrolbuff+=4;
  433. }
  434. /* 
  435. BOOL   DeviceIoControl(       
  436.   HANDLE   hDevice, //   handle   to   device   of   interest   
  437.   DWORD   dwIoControlCode, //   control   code   of   operation   to   perform   
  438.   LPVOID   lpInBuffer, //   pointer   to   buffer   to   supply   input   data   
  439.   DWORD   nInBufferSize, //   size   of   input   buffer   
  440.   LPVOID   lpOutBuffer, //   pointer   to   buffer   to   receive   output   data   
  441.   DWORD   nOutBufferSize, //   size   of   output   buffer   
  442.   LPDWORD   lpBytesReturned, //   pointer   to   variable   to   receive   output   byte   count   
  443.   LPOVERLAPPED   lpOverlapped   //   pointer   to   overlapped   structure   for   asynchronous   operation   
  444. ); */
  445. DeviceIoControl(device,IOCTL_BEHAVIORMON_HOOK,controlbuff,2048,controlbuff,2048,&dw,0);
  446. //控制定时器程序开始按时向驱动请求输出拦截到的行为数据
  447. Capture=TRUE;
  448. }
  449. //////////////////////////////////////////////////////////////////////////
  450. void CBehaviorMonView::unhook()
  451. {
  452. DWORD controlbuff[2048];
  453. DWORD dw;
  454. ZeroMemory(controlbuff,2048); 
  455. //打开设备
  456. if(!device)
  457. device=CreateFile("\\.\BEHAVIORMON",GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_SYSTEM,0);
  458. //控制设备
  459. DeviceIoControl(device,IOCTL_BEHAVIORMON_UNHOOK,controlbuff,2048,controlbuff,2048,&dw,0);
  460. }
  461. //////////////////////////////////////////////////////////////////////////
  462. void CBehaviorMonView::tell_driver_processname(CString processname)
  463. {
  464. DWORD controlbuff[2048];
  465. DWORD dw;
  466. ZeroMemory(controlbuff,2048);
  467. memcpy(controlbuff,processname,processname.GetLength()); 
  468. //打开设备
  469. if(!device)
  470. device=CreateFile("\\.\BEHAVIORMON",GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_SYSTEM,0);
  471. //控制设备,告诉驱动要监控的程序全路径
  472. DeviceIoControl(device,IOCTL_BEHAVIORMON_PROC,controlbuff,2048,controlbuff,2048,&dw,0);
  473. }
  474. /////////////////////////////////////////////////////////////////////////////
  475. // CBehaviorMonView diagnostics
  476. #ifdef _DEBUG
  477. void CBehaviorMonView::AssertValid() const
  478. {
  479. CFormView::AssertValid();
  480. }
  481. void CBehaviorMonView::Dump(CDumpContext& dc) const
  482. {
  483. CFormView::Dump(dc);
  484. }
  485. CBehaviorMonDoc* CBehaviorMonView::GetDocument() // non-debug version is inline
  486. {
  487. ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CBehaviorMonDoc)));
  488. return (CBehaviorMonDoc*)m_pDocument;
  489. }
  490. #endif //_DEBUG
  491. /////////////////////////////////////////////////////////////////////////////
  492. // CBehaviorMonView message handlers
  493. void CBehaviorMonView::OnClose() 
  494. {
  495. // TODO: Add your message handler code here and/or call default
  496. KillTimer( 1 );
  497. CFormView::OnClose(); 
  498. }
  499. void CBehaviorMonView::OnSize(UINT nType, int cx, int cy) 
  500. {
  501. CFormView::OnSize(nType, cx, cy);
  502. // TODO: Add your message handler code here
  503. CRect   rect;   
  504. this->GetWindowRect(&rect);   
  505. CRect   rect_button;
  506. CWnd   *pList   =   this->GetDlgItem(IDC_LIST_BEHAVIOR); 
  507. CWnd   *pButton_Hook   =   this->GetDlgItem(IDC_BUTTON_HOOK); 
  508. CWnd   *pButton_Unhook   =   this->GetDlgItem(IDC_BUTTON_UNHOOK); 
  509. CWnd   *pStatic_row   =   this->GetDlgItem(IDC_STATIC_ROW);
  510. if(pList != NULL){   
  511. pList->ScreenToClient(&rect);   
  512. pList->SetWindowPos(NULL,5,0,rect.Width()-15,rect.Height()-40,SWP_NOZORDER | SWP_NOACTIVATE);      
  513. }  
  514. if(pButton_Hook != NULL){   
  515. pButton_Hook->GetWindowRect(&rect_button); 
  516. pButton_Hook->ScreenToClient(&rect);   
  517. pButton_Hook->SetWindowPos(NULL,10,rect.Height()-30,rect_button.Width(),rect_button.Height(),SWP_NOZORDER | SWP_NOACTIVATE);      
  518. }  
  519. if(pButton_Unhook != NULL){   
  520. pButton_Unhook->GetWindowRect(&rect_button); 
  521. pButton_Unhook->ScreenToClient(&rect);   
  522. pButton_Unhook->SetWindowPos(NULL,10+rect_button.Width()+5,rect.Height()-30,rect_button.Width(),rect_button.Height(),SWP_NOZORDER | SWP_NOACTIVATE);      
  523. }  
  524. if(pStatic_row != NULL){   
  525. pStatic_row->GetWindowRect(&rect_button); 
  526. pStatic_row->ScreenToClient(&rect);   
  527. pStatic_row->SetWindowPos(NULL,rect.Width()-60,rect.Height()-30,rect_button.Width(),rect_button.Height(),SWP_NOZORDER | SWP_NOACTIVATE);      
  528. }
  529. void CBehaviorMonView::OnClickListBehavior(NMHDR* pNMHDR, LRESULT* pResult) 
  530. {
  531. // TODO: Add your control notification handler code here
  532. *pResult = 0;
  533. }
  534. void CBehaviorMonView::OnButtonHook() 
  535. {
  536. // TODO: Add your control notification handler code here
  537. if(!IsSetup)
  538. {
  539. setup();
  540. IsSetup=TRUE;
  541. }
  542. hook();
  543. CWnd   *pButton_Hook   =   this->GetDlgItem(IDC_BUTTON_HOOK); 
  544. CWnd   *pButton_Unhook   =   this->GetDlgItem(IDC_BUTTON_UNHOOK); 
  545. pButton_Hook->EnableWindow(FALSE);
  546. pButton_Unhook->EnableWindow(TRUE);
  547. }
  548. void CBehaviorMonView::OnButtonUnhook() 
  549. {
  550. // TODO: Add your control notification handler code here
  551. unhook();
  552. CWnd   *pButton_Hook   =   this->GetDlgItem(IDC_BUTTON_HOOK); 
  553. CWnd   *pButton_Unhook   =   this->GetDlgItem(IDC_BUTTON_UNHOOK); 
  554. pButton_Unhook->EnableWindow(FALSE);
  555. pButton_Hook->EnableWindow(TRUE);
  556. }
  557. void CBehaviorMonView::OnTimer(UINT nIDEvent) 
  558. {
  559. int j; 
  560. char name[1024];
  561. char row_num[20];
  562. PENTRY ptr;
  563. size_t  len;
  564. PCHAR Buffer;
  565. DWORD BufLen;
  566. char *items[NUMCOLUMNS];
  567. int itemcnt = 0; 
  568. float elapsed;
  569. char timeBuf[64], timeSub[64];
  570. int msIndex = 0; 
  571. char *secondsPtr;
  572. FILETIME localTime;
  573. SYSTEMTIME systemTime;
  574. LONGLONG time;
  575. LONGLONG perftime;
  576. // Time to query the device driver for more data
  577. if ( Capture )  {
  578. //打开设备
  579. if(!device)
  580. device=CreateFile("\\.\BEHAVIORMON",GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_SYSTEM,0);
  581. // don't process for more than a second without pausing
  582. startTime = GetTickCount();
  583. for (;;)  {
  584. // Have driver fill Stats buffer with information
  585. if ( ! DeviceIoControl( device, IOCTL_BEHAVIORMON_GETSTATS,
  586. NULL, 0, &Stats, sizeof Stats,
  587. &StatsLen, NULL ) )
  588. {
  589. //AfxMessageBox("Couldn't access device driver");
  590. return;
  591. }
  592. if ( StatsLen == 0 || StatsLen == 1 )
  593. break;
  594. // Update statistics windows
  595. // 向列表中添加一行 
  596. //得到程序名+完整路径
  597. Buffer=Stats;
  598. BufLen=StatsLen;
  599. for ( ptr = (PENTRY)Buffer; (char *)ptr < min(Buffer+BufLen,Buffer + LOGBUFSIZE); )  {
  600. len = strlen(ptr->text);
  601. len += 4; len &= 0xFFFFFFFC; // +1 for null-terminator +3 for 32bit alignment
  602. //----------------------------------------------------------- 
  603. // Split line into columns
  604. itemcnt = Split( ptr->text, 't', items );
  605. if ( itemcnt == 0 )
  606. return;
  607. strcpy(name,items[0]); 
  608. strcat(name,"(");
  609. //进程的完整路径
  610. strcat(name,items[2]);
  611. strcat(name,")");
  612. //得到进程图标
  613. hIcon=ExtractIcon(AfxGetInstanceHandle(),items[2],0);
  614. if(hIcon!=NULL)   
  615. j=images.Add(hIcon); 
  616. else
  617. {
  618. hIcon=AfxGetApp()->LoadIcon(IDI_ICON_DEFAULT);
  619. j=images.Add(hIcon);
  620. time=ptr->time.QuadPart;
  621. perftime=ptr->perftime.QuadPart;
  622. // format timestamp according to user preference
  623. if( ClockTime ) {
  624. if( IsNT ) {
  625. FileTimeToLocalFileTime( (PFILETIME) &time, &localTime );
  626. FileTimeToSystemTime( &localTime, &systemTime );
  627. } else {
  628. DosDateTimeToFileTime( (WORD) (time >> 48), (WORD) (time >> 32), &localTime );
  629. FileTimeToSystemTime( &localTime, &systemTime );
  630. systemTime.wSecond += ((WORD) time) / 1000;
  631. systemTime.wMilliseconds = ((WORD) time) % 1000;
  632. }
  633. GetTimeFormat( LOCALE_USER_DEFAULT, 0,
  634. &systemTime, NULL, timeBuf, 64 ); 
  635. secondsPtr = strrchr( timeBuf, ':');
  636. msIndex = (DWORD) (secondsPtr - timeBuf);
  637. while( timeBuf[msIndex] && timeBuf[msIndex] != ' ') msIndex++;
  638. strcpy( timeSub, &timeBuf[msIndex] );
  639. timeBuf[ msIndex ] = 0;
  640. sprintf( msgbuf, "%s.%03d%s", timeBuf, systemTime.wMilliseconds, timeSub );
  641.  
  642. } else {
  643. // convert to elapsed microseconds since start of regmon or last
  644. // gui clear
  645. if( IsNT ) {
  646. elapsed = ((float) perftime)/(float)PerfFrequency.QuadPart;
  647. sprintf( msgbuf, "%10.8f", elapsed );
  648. } else {
  649. sprintf( msgbuf, "%10.8f", perftime * 0.8 / 1e6);
  650. }
  651.  
  652. //得到序号
  653. ltoa(num,num_s,10);
  654. //加入列表中
  655. m_list_behavior.AddItem(
  656. j,//图标号
  657. num_s,//序号#
  658. _T(msgbuf),// time 
  659. _T(name),//processname:pid
  660. _T(items[1]),//NativeAPIname
  661. _T(items[4]),//Behavior 
  662. _T(items[3]));//result
  663. num++; 
  664. //显示目前提取了多少个行为 
  665. itoa(num,row_num,10); 
  666. strcat(row_num,"个行为");
  667. m_list_behavior.GetParent()->SetDlgItemText(IDC_STATIC_ROW,row_num);
  668. //-----------------------------------------------------------
  669. ptr = (PENTRY)(ptr->text + len);
  670. }
  671. //////////////////////////////////////////////////
  672. if( GetTickCount() - startTime > 1000 ) break;
  673. }
  674. }
  675. CFormView::OnTimer(nIDEvent);
  676. }
  677. int CBehaviorMonView::OnCreate(LPCREATESTRUCT lpCreateStruct) 
  678. {
  679. if (CFormView::OnCreate(lpCreateStruct) == -1)
  680. return -1;
  681. // TODO: Add your specialized creation code here
  682. SetTimer( 1, 500/*ms*/, NULL );
  683. // determine performance counter frequency
  684. QueryPerformanceFrequency( &PerfFrequency );
  685. return 0;
  686. }