BehaviorMonView.cpp
上传用户:xuemeng126
上传日期:2022-07-05
资源大小:454k
文件大小:23k
- // BehaviorMonView.cpp : implementation of the CBehaviorMonView class
- //
- #include "stdafx.h"
- #include "BehaviorMon.h"
- #include "BehaviorMonDoc.h"
- #include "BehaviorMonView.h"
- #include "IoctlCmd.h"
- #include <tchar.h>
- #include <commctrl.h>
- #include <stdio.h>
- #include <string.h>
- #include <winioctl.h>
- #ifdef _DEBUG
- #define new DEBUG_NEW
- #undef THIS_FILE
- static char THIS_FILE[] = __FILE__;
- #endif
- //宏定义
- // Number of columns in the listview
- #define NUMCOLUMNS 7
- // maximum length of an entier listview line
- #define MAXITEMLENGTH 0x1000
- //静态变量,可以在线程中使用
- static CSortListCtrl m_list_behavior;
- static CImageList images;
- static CString m_row_num;
- static HICON hIcon;
- static long num=0;
- static char num_s[32];
- static SYSTEMTIME local_time;
- static char processname[16];
- static char processfullname[512];
- static char nativeAPIname[64];
- static char behavior[1024];
- static char result[64];
- static DWORD b=0;
- //保存被hook的nativeAPI函数信息
- typedef struct {
- const char * nativeAPIname;//函数名称
- //ULONG Index;//在描述符表中的代号
- //ULONG RealCallee;//真正的地址
- //ULONG proxyfunadd;//代理函数地址
- //BOOL hooked;
- }HOOKED_API_INFO;
- static HOOKED_API_INFO hook_API_info[100];
- static int hook_num=0;
- //交互缓冲区,驱动往里写,前台往出读,做显示
- typedef struct{
- char IsRead;
- char ProcessName[32];
- char NativeAPIName[32];
- char ProcessFullName[512];
- char Behavior[1024];
- char Result[64];
- char Time[16];
- }LOG_BEHAVIOR;
- static LOG_BEHAVIOR log_behavior[10];
- static int curr_read_pointer=0;
- static int LOG_BEHAVIOR_NUM=10;
- /////////////////////////////////////////////////////////////////////////////
- static HINSTANCE hInst; // current instance 当前实例
- static HANDLE device;
- static char outputbuff[2048];
- static char processnamebuff[2048];
- static char * strings[256];
- static DWORD stringcount;
- static HANDLE hThread;
- static BOOL IsSetup;
- static BOOLEAN Capture = FALSE;
- static DWORD startTime;
- // Buffer into which driver can copy statistics
- char Stats[ LOGBUFSIZE ];
- // Current fraction of buffer filled
- DWORD StatsLen;
- static BOOLEAN ClockTime = TRUE;
- static BOOLEAN IsNT= TRUE;
- // General buffer for storing temporary strings
- static TCHAR msgbuf[ MAXITEMLENGTH ];
- // performance counter frequency
- LARGE_INTEGER PerfFrequency;
- // CBehaviorMonView
- IMPLEMENT_DYNCREATE(CBehaviorMonView, CFormView)
- BEGIN_MESSAGE_MAP(CBehaviorMonView, CFormView)
- //{{AFX_MSG_MAP(CBehaviorMonView)
- ON_WM_CLOSE()
- ON_WM_SIZE()
- ON_NOTIFY(NM_CLICK, IDC_LIST_BEHAVIOR, OnClickListBehavior)
- ON_WM_TIMER()
- ON_BN_CLICKED(IDC_BUTTON_HOOK, OnButtonHook)
- ON_BN_CLICKED(IDC_BUTTON_UNHOOK, OnButtonUnhook)
- ON_WM_CREATE()
- //}}AFX_MSG_MAP
- // Standard printing commands
- ON_COMMAND(ID_FILE_PRINT, CFormView::OnFilePrint)
- ON_COMMAND(ID_FILE_PRINT_DIRECT, CFormView::OnFilePrint)
- ON_COMMAND(ID_FILE_PRINT_PREVIEW, CFormView::OnFilePrintPreview)
- END_MESSAGE_MAP()
- /////////////////////////////////////////////////////////////////////////////
- // CBehaviorMonView construction/destruction
- CBehaviorMonView::CBehaviorMonView()
- : CFormView(CBehaviorMonView::IDD)
- {
- //{{AFX_DATA_INIT(CBehaviorMonView)
- m_row_num = _T("");
- //}}AFX_DATA_INIT
- // TODO: add construction code here
- setup();
- IsSetup=TRUE;
- }
- CBehaviorMonView::~CBehaviorMonView()
- {
- cleanup();
- }
- void CBehaviorMonView::DoDataExchange(CDataExchange* pDX)
- {
- CFormView::DoDataExchange(pDX);
- //{{AFX_DATA_MAP(CBehaviorMonView)
- DDX_Control(pDX, IDC_LIST_BEHAVIOR, m_list_behavior);
- DDX_Text(pDX, IDC_STATIC_ROW, m_row_num);
- //}}AFX_DATA_MAP
- }
- BOOL CBehaviorMonView::PreCreateWindow(CREATESTRUCT& cs)
- {
- // TODO: Modify the Window class or styles here by modifying
- // the CREATESTRUCT cs
- return CFormView::PreCreateWindow(cs);
- }
- void CBehaviorMonView::OnInitialUpdate()
- {
- CFormView::OnInitialUpdate();
- GetParentFrame()->RecalcLayout();
- ResizeParentToFit();
- m_list_behavior.SetHeadings( _T("#,40;Time,90;Process Name,200;Native API,100;Behavior,500;Result,60") ); ///设置列头信息
- m_list_behavior.LoadColumnInfo(); ///加载列信息
- //CListCtrl扩展样式改变
- DWORD dwStyle;
- dwStyle = m_list_behavior.GetStyle(); //取得样式
- dwStyle |= LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT | LVS_EX_HEADERDRAGDROP ; //添加样式
- m_list_behavior.SetExtendedStyle(dwStyle); //重新设置
- /*
- m_list_behavior.SetExtendedStyle(
- //LVS_EX_ONECLICKACTIVATE //单击选中项
- | LVS_EX_FULLROWSELECT // 答应整行选中
- | LVS_EX_HEADERDRAGDROP // 答应标题拖拽
- | LVS_SHOWSELALWAYS //高亮度显示被选中项
- | LVS_EX_GRIDLINES //网格线
- | LVS_EX_FLATSB // 扁平风格滚动
- ); */
- images.Create(16,16,ILC_COLOR32 ,10,10);
- m_list_behavior.SetImageList(&images,LVSIL_SMALL);
- //for test
- /*
- hIcon=AfxGetApp()->LoadIcon(IDI_ICON_DEFAULT);
- int j=images.Add(hIcon);
- GetLocalTime(&local_time);
- ltoa(num,num_s,10);
- CString strTime;
- strTime.Format(_T("%.2d:%.2d:%.2d.%.3d"),local_time.wHour,local_time.wMinute,local_time.wSecond,local_time.wMilliseconds);
- m_list_behavior.AddItem(j,num_s,strTime, _T("是"),_T("是"),_T("是"),_T("是"));///添加表项
- num++;
- */
- CWnd *pButton_Unhook = this->GetDlgItem(IDC_BUTTON_UNHOOK);
- pButton_Unhook->EnableWindow(FALSE);
- }
- /////////////////////////////////////////////////////////////////////////////
- // CBehaviorMonView printing
- BOOL CBehaviorMonView::OnPreparePrinting(CPrintInfo* pInfo)
- {
- // default preparation
- return DoPreparePrinting(pInfo);
- }
- void CBehaviorMonView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
- {
- // TODO: add extra initialization before printing
- }
- void CBehaviorMonView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
- {
- // TODO: add cleanup after printing
- }
- void CBehaviorMonView::OnPrint(CDC* pDC, CPrintInfo* /*pInfo*/)
- {
- // TODO: add customized printing code here
- }
- //*********************************************************************************
- void CBehaviorMonView::clear_list()
- {
- m_list_behavior.DeleteAllItems();
- num=0;
- char row_num[10];
- itoa(num,row_num,10);
- strcat(row_num,"个行为");
- m_list_behavior.GetParent()->SetDlgItemText(IDC_STATIC_ROW,row_num);
- }
- /******************************************************************************
- *
- * FUNCTION: Split
- *
- * PURPOSE: Split a delimited line into components
- *
- ******************************************************************************/
- int Split( char * line, char delimiter, char * items[] )
- {
- int cnt = 0;
- for (;;) {
- // Add prefix to list of components
- items[cnt++] = line;
- // Check for more components
- line = strchr( line, delimiter );
- if ( line == NULL )
- return cnt;
- // Terminate previous component and move to next
- *line++ = ' ';
- }
- }
- void displayError(char * s)
- {
- LPVOID lpMsgBuf;
- FormatMessage(
- FORMAT_MESSAGE_ALLOCATE_BUFFER |
- FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_IGNORE_INSERTS,
- NULL,
- GetLastError(),
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
- (LPTSTR) &lpMsgBuf,
- 0,
- NULL
- );
-
- // Process any inserts in lpMsgBuf.
- // ...
-
- // Display the string.
- CString cs=CString(s)+" "+(LPCTSTR)lpMsgBuf;
- AfxMessageBox(cs);
-
- // Free the buffer.
- LocalFree( lpMsgBuf );
- }
- //安装设备驱动
- //安装了设备驱动后,设备驱动程序中负责创建一个新的虚拟设备
- void CBehaviorMonView::setup()
- {
- char namebuff[256];
- //get path to ths .sys.file
- GetModuleFileName(0,namebuff,256);
- DWORD a=strlen(namebuff);
- while(1)
- {
- if(namebuff[a]=='\')break;
- a--;
- }
- a++;
- strcpy(&namebuff[a], "BehaviorMon.sys");
- /*
- 安装驱动程序流程:
- 1,调用OpenSCManager()打开服务控制管理器
- 2,调用CreateService()创建一个服务,服务类型为内核驱动
- 3,调用OpenService()取得服务句柄,启动服务
- 4,调用StartService()启动服务,停止服务
- 4,调用ControlService()停止服务,删除服务
- 4,调用DeleteService()删除服务
- 5,调用CloseServiceHandle()关闭服务句柄
- */
- //create service
- //system("msiexec /unregserver");
- SC_HANDLE t;SERVICE_STATUS stat;
- SC_HANDLE man=OpenSCManager(0,0,SC_MANAGER_ALL_ACCESS);
- t=OpenService(man,"behaviormonservice",SERVICE_ALL_ACCESS);
- ControlService(t,SERVICE_CONTROL_STOP,&stat);
- DeleteService(t);
- CloseServiceHandle(t);
- if(man==NULL)
- {
- displayError("打开服务管理器失败!");
- }
- t=CreateService(man,"behaviormonservice","behaviormonservice",
- SERVICE_START|SERVICE_STOP,SERVICE_KERNEL_DRIVER,SERVICE_DEMAND_START,SERVICE_ERROR_NORMAL,namebuff,0,0,0,0,0);
- if(t==NULL)
- {
- displayError("创建服务失败!");
- }
- if(0==StartService(t,0,0))
- {
- displayError("启动服务失败!");
- }
- }
- //*********************************************************************************
- void CBehaviorMonView::cleanup()
- {
- //结束线程hThread
- //TerminateThread(hThread,0);
- Capture=FALSE;
- Sleep(1500);
- unhook();
- SC_HANDLE man;
- if((man=OpenSCManager(0,0,SC_MANAGER_ALL_ACCESS))==NULL)
- {
- displayError("打开服务管理器失败!");
- }
- SERVICE_STATUS stat;
- SC_HANDLE t;
- if((t=OpenService(man,"behaviormonservice",SERVICE_ALL_ACCESS))==NULL)
- {
- displayError("打开服务失败!");
- }
- if(ControlService(t,SERVICE_CONTROL_STOP,&stat)==0)
- {
- displayError("控制服务失败!");
- }
- if (! DeleteService(t) )
- {
- displayError("设备驱动卸载失败!");
- }
- if(!CloseServiceHandle(t))
- {
- displayError("关闭服务句柄失败!");
- }
- IsSetup=FALSE;
- }
- //*********************************************************************************
- //线程函数
- //*********************************************************************************
- static void threadfun()
- {
- int j;
- char name[1024];
- char row_num[20];
- while(1)
- {
- while(log_behavior[curr_read_pointer].IsRead=='y')
- {
- Sleep(100);
- continue;
- }
- //得到程序名+完整路径
- strcpy(name,log_behavior[curr_read_pointer].ProcessName);
- strcat(name,"(");
- //进程的完整路径,用这个路径可以得到图标
- strcat(name,log_behavior[curr_read_pointer].ProcessFullName);
- strcat(name,")");
- //得到进程图标
- hIcon=ExtractIcon(AfxGetInstanceHandle(),log_behavior[curr_read_pointer].ProcessFullName,0);
- if(hIcon!=NULL)
- j=images.Add(hIcon);
- else
- {
- hIcon=AfxGetApp()->LoadIcon(IDI_ICON_DEFAULT);
- j=images.Add(hIcon);
- }
- //得到序号
- ltoa(num,num_s,10);
- //加入列表中
- m_list_behavior.AddItem(
- j,//图标号
- num_s,//序号#
- _T(log_behavior[curr_read_pointer].Time),// time
- //_T("time"),
- _T(name),//processname:pid
- _T(log_behavior[curr_read_pointer].NativeAPIName),//NativeAPIname
- _T(log_behavior[curr_read_pointer].Behavior),//Behavior
- //_T("behavior"),
- _T("允许"));//result
- num++;
- //读取完成
- log_behavior[curr_read_pointer].IsRead='y';
- curr_read_pointer++;
- if(curr_read_pointer==LOG_BEHAVIOR_NUM)
- curr_read_pointer=0;
- //显示目前提取了多少个行为
- itoa(num,row_num,10);
- strcat(row_num,"个行为");
- m_list_behavior.GetParent()->SetDlgItemText(IDC_STATIC_ROW,row_num);
- }
- }
- //让驱动hook SSDT中指定的Native API
- void CBehaviorMonView::hook()
- {
- int i;
- hook_num=0;
- hook_API_info[hook_num++].nativeAPIname="NtRestoreKey";
- hook_API_info[hook_num++].nativeAPIname="NtOpenKey";
- hook_API_info[hook_num++].nativeAPIname="NtCreateKey";
- hook_API_info[hook_num++].nativeAPIname="NtQueryValueKey";
- hook_API_info[hook_num++].nativeAPIname="NtQueryKey";
- hook_API_info[hook_num++].nativeAPIname="NtDeleteKey";
- hook_API_info[hook_num++].nativeAPIname="NtDeleteValueKey";
- hook_API_info[hook_num++].nativeAPIname="NtSetValueKey";
- hook_API_info[hook_num++].nativeAPIname="NtEnumerateKey";
- hook_API_info[hook_num++].nativeAPIname="NtEnumerateValueKey";
- hook_API_info[hook_num++].nativeAPIname="NtOpenFile";
- hook_API_info[hook_num++].nativeAPIname="NtWriteFile";
- hook_API_info[hook_num++].nativeAPIname="NtCreateFile";
- hook_API_info[hook_num++].nativeAPIname="NtCreateProcess";
- hook_API_info[hook_num++].nativeAPIname="NtCreateProcessEx";
- hook_API_info[hook_num++].nativeAPIname="NtCreateSection";
- hook_API_info[hook_num++].nativeAPIname="NtOpenThread";
- hook_API_info[hook_num++].nativeAPIname="NtCreateThread";
- hook_API_info[hook_num++].nativeAPIname="NtOpenProcess";
- hook_API_info[hook_num++].nativeAPIname="NtOpenSection";
- hook_API_info[hook_num++].nativeAPIname="NtCreateSymbolicLinkObject";
- hook_API_info[hook_num++].nativeAPIname="NtSetSystemTime";
- //安装设备驱动
- //setup();
- //MessageBox("设备驱动安装成功!","提示",MB_OK);
- DWORD controlbuff[2048];
- DWORD dw;
-
- //打开设备
- if(!device)
- device=CreateFile("\\.\BEHAVIORMON",GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_SYSTEM,0);
- // Have driver zero information
- if ( ! DeviceIoControl( device, IOCTL_BEHAVIORMON_ZEROSTATS,NULL, 0, NULL, 0, &dw, NULL ) )
- {
- return;
- }
- //告诉后台驱动hook上面的函数
- char * pcontrolbuff=(char *)controlbuff;
- int offsetcontrolbuff=0;
- //填写交换缓冲区的地址
- controlbuff[0]=(DWORD)&log_behavior[0];
- offsetcontrolbuff+=4;
- //填写LOG_BEHAVIOR数组的大小
- controlbuff[1]=LOG_BEHAVIOR_NUM;
- offsetcontrolbuff+=4;
- //被Hook的NativeAPI的总个数
- controlbuff[2]=hook_num;
- offsetcontrolbuff+=4;
- //把前面要Hook的Native API函数的基本信息(name,index)写入controlbuff
- for(i=0;i<hook_num;i++)
- {
- DWORD * addr=(DWORD *)(1+(DWORD)GetProcAddress(GetModuleHandle("ntdll.dll"),hook_API_info[i].nativeAPIname));
- //被Hook的NativeAPI的名称
- strcpy(pcontrolbuff+offsetcontrolbuff,hook_API_info[i].nativeAPIname);
- offsetcontrolbuff+=strlen(hook_API_info[i].nativeAPIname);
- offsetcontrolbuff+=1;
- //被Hook的NativeAPI的Index
- //controlbuff[2]=addr[0];//函数调用地址的地址
- memmove(pcontrolbuff+offsetcontrolbuff,&addr[0],4);
- offsetcontrolbuff+=4;
- }
- /*
- BOOL DeviceIoControl(
- HANDLE hDevice, // handle to device of interest
- DWORD dwIoControlCode, // control code of operation to perform
- LPVOID lpInBuffer, // pointer to buffer to supply input data
- DWORD nInBufferSize, // size of input buffer
- LPVOID lpOutBuffer, // pointer to buffer to receive output data
- DWORD nOutBufferSize, // size of output buffer
- LPDWORD lpBytesReturned, // pointer to variable to receive output byte count
- LPOVERLAPPED lpOverlapped // pointer to overlapped structure for asynchronous operation
- ); */
- DeviceIoControl(device,IOCTL_BEHAVIORMON_HOOK,controlbuff,2048,controlbuff,2048,&dw,0);
- //控制定时器程序开始按时向驱动请求输出拦截到的行为数据
- Capture=TRUE;
- }
- //////////////////////////////////////////////////////////////////////////
- void CBehaviorMonView::unhook()
- {
- DWORD controlbuff[2048];
- DWORD dw;
- ZeroMemory(controlbuff,2048);
- //打开设备
- if(!device)
- device=CreateFile("\\.\BEHAVIORMON",GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_SYSTEM,0);
- //控制设备
- DeviceIoControl(device,IOCTL_BEHAVIORMON_UNHOOK,controlbuff,2048,controlbuff,2048,&dw,0);
- }
- //////////////////////////////////////////////////////////////////////////
- void CBehaviorMonView::tell_driver_processname(CString processname)
- {
- DWORD controlbuff[2048];
- DWORD dw;
- ZeroMemory(controlbuff,2048);
- memcpy(controlbuff,processname,processname.GetLength());
- //打开设备
- if(!device)
- device=CreateFile("\\.\BEHAVIORMON",GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_SYSTEM,0);
- //控制设备,告诉驱动要监控的程序全路径
- DeviceIoControl(device,IOCTL_BEHAVIORMON_PROC,controlbuff,2048,controlbuff,2048,&dw,0);
- }
- /////////////////////////////////////////////////////////////////////////////
- // CBehaviorMonView diagnostics
- #ifdef _DEBUG
- void CBehaviorMonView::AssertValid() const
- {
- CFormView::AssertValid();
- }
- void CBehaviorMonView::Dump(CDumpContext& dc) const
- {
- CFormView::Dump(dc);
- }
- CBehaviorMonDoc* CBehaviorMonView::GetDocument() // non-debug version is inline
- {
- ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CBehaviorMonDoc)));
- return (CBehaviorMonDoc*)m_pDocument;
- }
- #endif //_DEBUG
- /////////////////////////////////////////////////////////////////////////////
- // CBehaviorMonView message handlers
- void CBehaviorMonView::OnClose()
- {
- // TODO: Add your message handler code here and/or call default
- KillTimer( 1 );
- CFormView::OnClose();
- }
- void CBehaviorMonView::OnSize(UINT nType, int cx, int cy)
- {
- CFormView::OnSize(nType, cx, cy);
-
- // TODO: Add your message handler code here
- CRect rect;
- this->GetWindowRect(&rect);
- CRect rect_button;
- CWnd *pList = this->GetDlgItem(IDC_LIST_BEHAVIOR);
- CWnd *pButton_Hook = this->GetDlgItem(IDC_BUTTON_HOOK);
- CWnd *pButton_Unhook = this->GetDlgItem(IDC_BUTTON_UNHOOK);
- CWnd *pStatic_row = this->GetDlgItem(IDC_STATIC_ROW);
- if(pList != NULL){
- pList->ScreenToClient(&rect);
- pList->SetWindowPos(NULL,5,0,rect.Width()-15,rect.Height()-40,SWP_NOZORDER | SWP_NOACTIVATE);
- }
- if(pButton_Hook != NULL){
- pButton_Hook->GetWindowRect(&rect_button);
- pButton_Hook->ScreenToClient(&rect);
- pButton_Hook->SetWindowPos(NULL,10,rect.Height()-30,rect_button.Width(),rect_button.Height(),SWP_NOZORDER | SWP_NOACTIVATE);
- }
- if(pButton_Unhook != NULL){
- pButton_Unhook->GetWindowRect(&rect_button);
- pButton_Unhook->ScreenToClient(&rect);
- pButton_Unhook->SetWindowPos(NULL,10+rect_button.Width()+5,rect.Height()-30,rect_button.Width(),rect_button.Height(),SWP_NOZORDER | SWP_NOACTIVATE);
- }
- if(pStatic_row != NULL){
- pStatic_row->GetWindowRect(&rect_button);
- pStatic_row->ScreenToClient(&rect);
- pStatic_row->SetWindowPos(NULL,rect.Width()-60,rect.Height()-30,rect_button.Width(),rect_button.Height(),SWP_NOZORDER | SWP_NOACTIVATE);
- }
- }
- void CBehaviorMonView::OnClickListBehavior(NMHDR* pNMHDR, LRESULT* pResult)
- {
- // TODO: Add your control notification handler code here
-
- *pResult = 0;
- }
- void CBehaviorMonView::OnButtonHook()
- {
- // TODO: Add your control notification handler code here
- if(!IsSetup)
- {
- setup();
- IsSetup=TRUE;
- }
- hook();
- CWnd *pButton_Hook = this->GetDlgItem(IDC_BUTTON_HOOK);
- CWnd *pButton_Unhook = this->GetDlgItem(IDC_BUTTON_UNHOOK);
- pButton_Hook->EnableWindow(FALSE);
- pButton_Unhook->EnableWindow(TRUE);
- }
- void CBehaviorMonView::OnButtonUnhook()
- {
- // TODO: Add your control notification handler code here
- unhook();
- CWnd *pButton_Hook = this->GetDlgItem(IDC_BUTTON_HOOK);
- CWnd *pButton_Unhook = this->GetDlgItem(IDC_BUTTON_UNHOOK);
- pButton_Unhook->EnableWindow(FALSE);
- pButton_Hook->EnableWindow(TRUE);
- }
- void CBehaviorMonView::OnTimer(UINT nIDEvent)
- {
- int j;
- char name[1024];
- char row_num[20];
- PENTRY ptr;
- size_t len;
- PCHAR Buffer;
- DWORD BufLen;
- char *items[NUMCOLUMNS];
- int itemcnt = 0;
- float elapsed;
- char timeBuf[64], timeSub[64];
- int msIndex = 0;
- char *secondsPtr;
- FILETIME localTime;
- SYSTEMTIME systemTime;
- LONGLONG time;
- LONGLONG perftime;
- // Time to query the device driver for more data
- if ( Capture ) {
- //打开设备
- if(!device)
- device=CreateFile("\\.\BEHAVIORMON",GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_SYSTEM,0);
- // don't process for more than a second without pausing
- startTime = GetTickCount();
- for (;;) {
-
- // Have driver fill Stats buffer with information
- if ( ! DeviceIoControl( device, IOCTL_BEHAVIORMON_GETSTATS,
- NULL, 0, &Stats, sizeof Stats,
- &StatsLen, NULL ) )
- {
- //AfxMessageBox("Couldn't access device driver");
- return;
- }
- if ( StatsLen == 0 || StatsLen == 1 )
- break;
-
- // Update statistics windows
- // 向列表中添加一行
- //得到程序名+完整路径
- Buffer=Stats;
- BufLen=StatsLen;
- for ( ptr = (PENTRY)Buffer; (char *)ptr < min(Buffer+BufLen,Buffer + LOGBUFSIZE); ) {
-
- len = strlen(ptr->text);
- len += 4; len &= 0xFFFFFFFC; // +1 for null-terminator +3 for 32bit alignment
- //-----------------------------------------------------------
- // Split line into columns
- itemcnt = Split( ptr->text, 't', items );
- if ( itemcnt == 0 )
- return;
-
- strcpy(name,items[0]);
- strcat(name,"(");
- //进程的完整路径
- strcat(name,items[2]);
- strcat(name,")");
-
- //得到进程图标
- hIcon=ExtractIcon(AfxGetInstanceHandle(),items[2],0);
- if(hIcon!=NULL)
- j=images.Add(hIcon);
- else
- {
- hIcon=AfxGetApp()->LoadIcon(IDI_ICON_DEFAULT);
- j=images.Add(hIcon);
- }
-
- time=ptr->time.QuadPart;
- perftime=ptr->perftime.QuadPart;
- // format timestamp according to user preference
- if( ClockTime ) {
-
- if( IsNT ) {
- FileTimeToLocalFileTime( (PFILETIME) &time, &localTime );
- FileTimeToSystemTime( &localTime, &systemTime );
- } else {
- DosDateTimeToFileTime( (WORD) (time >> 48), (WORD) (time >> 32), &localTime );
- FileTimeToSystemTime( &localTime, &systemTime );
- systemTime.wSecond += ((WORD) time) / 1000;
- systemTime.wMilliseconds = ((WORD) time) % 1000;
- }
- GetTimeFormat( LOCALE_USER_DEFAULT, 0,
- &systemTime, NULL, timeBuf, 64 );
-
- secondsPtr = strrchr( timeBuf, ':');
- msIndex = (DWORD) (secondsPtr - timeBuf);
- while( timeBuf[msIndex] && timeBuf[msIndex] != ' ') msIndex++;
- strcpy( timeSub, &timeBuf[msIndex] );
- timeBuf[ msIndex ] = 0;
- sprintf( msgbuf, "%s.%03d%s", timeBuf, systemTime.wMilliseconds, timeSub );
-
- } else {
-
- // convert to elapsed microseconds since start of regmon or last
- // gui clear
- if( IsNT ) {
- elapsed = ((float) perftime)/(float)PerfFrequency.QuadPart;
- sprintf( msgbuf, "%10.8f", elapsed );
- } else {
- sprintf( msgbuf, "%10.8f", perftime * 0.8 / 1e6);
- }
- }
-
- //得到序号
- ltoa(num,num_s,10);
- //加入列表中
- m_list_behavior.AddItem(
- j,//图标号
- num_s,//序号#
- _T(msgbuf),// time
- _T(name),//processname:pid
- _T(items[1]),//NativeAPIname
- _T(items[4]),//Behavior
- _T(items[3]));//result
- num++;
- //显示目前提取了多少个行为
- itoa(num,row_num,10);
- strcat(row_num,"个行为");
- m_list_behavior.GetParent()->SetDlgItemText(IDC_STATIC_ROW,row_num);
- //-----------------------------------------------------------
- ptr = (PENTRY)(ptr->text + len);
- }
- //////////////////////////////////////////////////
- if( GetTickCount() - startTime > 1000 ) break;
- }
- }
- CFormView::OnTimer(nIDEvent);
- }
- int CBehaviorMonView::OnCreate(LPCREATESTRUCT lpCreateStruct)
- {
- if (CFormView::OnCreate(lpCreateStruct) == -1)
- return -1;
-
- // TODO: Add your specialized creation code here
- SetTimer( 1, 500/*ms*/, NULL );
- // determine performance counter frequency
- QueryPerformanceFrequency( &PerfFrequency );
- return 0;
- }