www.pudn.com > Process_Mo18292312142004.rar > xstdio.cpp
/*******************************************************
This file is part of Process Monitor.
Copyright (c) 2004 by Michel van Kerkhof, ( michel000@planet.nl http://home.wxs.nl/~wijk0550/ )
For more information consult the Readme file.
This program is free software; you can redistribute it
and/or modify it under the terms of the GNU
General Public License as published by the Free
Software Foundation; either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will
be useful, but WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU
General Public License along with this program;
if not, write to:
the Free Software Foundation, Inc.,
59 Temple Place,
Suite 330, Boston,
MA 02111-1307 USA
*******************************************************
If you like my work and you have a job for me please contact me at: michel000@planet.nl
*******************************************************/
#include "includes.h"
NTAPIS NtApi;
extern const char szWindowTitle[] = "Process Monitor 1.0";
/*
Function Description:
Shows a messagebox
Arguments:
IN hWnd Owner window
IN format format-control string
IN ... optional arguments
Returns:
void
*/
void ShowError(HWND hWnd,const char * format, ...)
{
char szError[512];
va_list argptr;
va_start(argptr,format);
wvsprintf(szError,format,argptr);
va_end(argptr);
MessageBox(hWnd,szError,szWindowTitle,0);
}
FARPROC xGetProcAddress(HINSTANCE hDll,char *szApi)
{
FARPROC Ret=GetProcAddress(hDll,szApi);
if (Ret) {
if (*(LPBYTE)Ret == 0xe9 ||
*(LPBYTE)((int)Ret + 1) == 0xe9
) {
if (NtApi.fGetModuleInformation) {
MODULEINFO mi;
if (NtApi.fGetModuleInformation(GetCurrentProcess(),hDll,&mi,sizeof(mi))) {
if ((int)mi.EntryPoint + (int)mi.SizeOfImage < *(int *)((int)Ret + 1) || (int)mi.EntryPoint > *(int *)((int)Ret + 1)) {
ShowError(NULL,"Hooked %s %0.2X %0.2X",szApi,*(LPBYTE)Ret,*(LPBYTE)((int)Ret + 1));
}
}
}
}
}
return Ret;
}
/*
Function Description:
Load all needed api's into NtApi array
Arguments:
Returns:
void
*/
void LoadApis()
{
HMODULE hDll;
hDll = LoadLibrary("PSAPI.DLL");
if (hDll) {
NtApi.fGetModuleInformation=(pGetModuleInformation)xGetProcAddress(hDll,"GetModuleInformation");
NtApi.fEnumProcesses=(pEnumProcesses)xGetProcAddress(hDll,"EnumProcesses");
NtApi.fEnumDeviceDrivers=(pEnumDeviceDrivers)xGetProcAddress(hDll,"EnumDeviceDrivers");
NtApi.fEnumProcessModules=(pEnumProcessModules)xGetProcAddress(hDll,"EnumProcessModules");
NtApi.fGetDeviceDriverFileName=(pGetDeviceDriverFileName)xGetProcAddress(hDll,"GetDeviceDriverFileNameA");
NtApi.fGetModuleFileNameEx=(pGetModuleFileNameEx)xGetProcAddress(hDll,"GetModuleFileNameExA");
}
xGetProcAddress(GetModuleHandle("kernel32.dll"),"GetProcessAddress");
xGetProcAddress(LoadLibrary("ws2_32.dll"),"send");
xGetProcAddress(LoadLibrary("ws2_32.dll"),"WSARecv");
xGetProcAddress(LoadLibrary("ws2_32.dll"),"recv");
hDll=LoadLibrary("kernel32.dll");
if (hDll) {
NtApi.fOpenThread =(pOpenThread) GetProcAddress(hDll,"OpenThread");
}
hDll=LoadLibrary("ntdll.dll");
if (hDll) {
NtApi.fNtQueryInformationProcess=(pNtQueryInformationProcess)xGetProcAddress(hDll,"NtQueryInformationProcess");
NtApi.fNtQueryInformationThread=(pNtQueryInformationThread)xGetProcAddress(hDll,"NtQueryInformationThread");
NtApi.fNTQueryObject=(pNTQueryObject)xGetProcAddress(hDll,"NtQueryObject");
NtApi.fNtQuerySystemInformation=(pNtQuerySystemInformation)xGetProcAddress(hDll,"NtQuerySystemInformation");
NtApi.fNtQueryInformationFile=(pNtQueryInformationFile)xGetProcAddress(hDll,"NtQueryInformationFile");
}
hDll=LoadLibrary("iphlpapi.dll");
if (hDll) {
NtApi.fnAllocateAndGetTcpExTableFromStack= (pAllocateAndGetTcpExTableFromStack)xGetProcAddress(hDll,"AllocateAndGetTcpExTableFromStack");
NtApi.fnAllocateAndGetUdpExTableFromStack= (pAllocateAndGetUdpExTableFromStack)xGetProcAddress(hDll,"AllocateAndGetUdpExTableFromStack");
NtApi.fSetTcpEntry= (pSetTcpEntry)xGetProcAddress(hDll,"SetTcpEntry");
}
hDll=LoadLibrary("advapi32.dll");
if (hDll) {
NtApi.fEnumServicesStatusExA=(pEnumServicesStatusExA)xGetProcAddress(hDll,"EnumServicesStatusExA");
}
hDll=LoadLibrary("Winsta.dll");
if (hDll) {
NtApi.fWinStationGetProcessSid=(pWinStationGetProcessSid)xGetProcAddress(hDll,"WinStationGetProcessSid");
}
hDll = LoadLibrary("utildll.dll");
if (hDll) {
NtApi.fCachedGetUserFromSid=(pCachedGetUserFromSid)xGetProcAddress(hDll,"CachedGetUserFromSid");
}
hDll=LoadLibrary("powrprof.dll");
if (hDll) {
NtApi.fSetSuspendState=(pSetSuspendState)xGetProcAddress(hDll,"SetSuspendState");
}
hDll=LoadLibrary("Shell32.dll");
if (hDll) {
NtApi.fOpenRunDlg=(pOpenRunDlg)xGetProcAddress(hDll, (LPSTR) 61);
}
}
/*
Function Description:
Convert a unsigned int to a char array
Arguments:
OUT buf, pointer to buffer for output
IN num, number to convert
IN len, sizeof(buf)
Returns:
strlen(buf);
*/
int inttochar(char *buf,unsigned int num,int len)
{
int i=0,x=1;
while (num / (x * 10) > 0) x=x * 10;
while (x > 0) {
if (num / x >= 0) {
*(buf+i)=(char)(num / x) + '0';
i++;
if (i >= len) {
i=0;
break;
}
}
num=num % x;
x=x/10;
}
*(buf+i)=0;
return i;
}
/*
Function Description:
Convert a LARGE_INTEGER to a char array
Arguments:
OUT buf, pointer to buffer for output
IN num, number to convert
IN len, sizeof(buf)
Returns:
pointer to outputbuf;
*/
char *largeinttochar(char *buf,LARGE_INTEGER *num,int len)
{
int i=0;
LARGE_INTEGER x;
x.QuadPart=1;
while (num->QuadPart / (x.QuadPart * 10) > 0) x.QuadPart=x.QuadPart * 10;
while (x.QuadPart > 0) {
if (num->QuadPart / x.QuadPart >= 0) {
*(buf+i)=(char)(num->QuadPart / x.QuadPart) + '0';
i++;
if (i >= len) {
i=0;
break;
}
}
num->QuadPart=num->QuadPart % x.QuadPart;
x.QuadPart=x.QuadPart/10;
}
*(buf+i)=0;
return buf;
}
/*
Function Description:
Convert Process FileName returned by some Functions to a filename on disk
\SystemRoot\System32\smss.exe to c:\Windows\System32\smss.exe
Arguments:
IN OUT szFile, pointer to buffer of old filename
and for new file name must be at least MAX_PATH in size
Returns:
pointer to new Filename this isnt always the same as szFile (pReturn == szFile+x)
*/
char *GetFileName(char *szFile)
{
char *pFile;
char szTemp[MAX_PATH];
pFile=strstr(szFile,"\\SystemRoot");
if (pFile) {
pFile++;
strcpy(szTemp,pFile+10);
GetWindowsDirectory(pFile,MAX_PATH-(pFile - szFile));
strcat(pFile,szTemp);
}
pFile=szFile;
if (_strnicmp(pFile,"\\WINDOWS\\",9) == 0) {
strcpy(szTemp,pFile+8);
GetWindowsDirectory(pFile,MAX_PATH);
strcat(pFile,szTemp);
}
if (*pFile == '\\') {
*pFile++;
if (*(pFile+1) == ':' && *(pFile+2) == '\\') return pFile;
while (*pFile && *pFile != '\\') pFile++;
if (*pFile == 0) pFile=szFile;
else pFile++;
}
return pFile;
}
/*
Function Description:
Gets the version info from a file
Arguments:
IN szFile, pointer to buffer of Filename
OUT pVersionInfo, pointer to array of strings containing version info
look add szVersionInfo[] to get discription
IN iLenghtString, lenght of strings
IN iNumofString, number of strings
Returns:
bool true if succesfull
*/
const char *szVersionInfo[]={
"FileDescription",
"CompanyName",
"FileVersion",
"InternalName",
"LegalCopyright",
"OriginalFilename",
"ProductName",
"ProductVersion",
NULL
};
bool GetFileInfo(char *szFileName,char *pVersionInfo,int iLenghtString,int iNumofStrings)
{
DWORD dwSize;
int Size,i;
//set array to "N\A"
for(i=0;i < iNumofStrings;i++)
strcpy(pVersionInfo+(i*iLenghtString),"N\\A");
Size = GetFileVersionInfoSize(szFileName,&dwSize);
if (Size < 1) return false;
void *Buf=malloc(Size);
if (!Buf) return false;
if (GetFileVersionInfo(szFileName,NULL,Size,Buf) == 0) {
free(Buf);
return false;
}
void *xBuf;
if (VerQueryValue(Buf,"\\VarFileInfo\\Translation",&xBuf,(unsigned int *)&Size) == 0) {
free(Buf);
return false;
}
WORD Lang,CharSet;
Lang=*(WORD *)xBuf;
CharSet=*((WORD *)((int)xBuf+2));
char szString[MAX_PATH];
for(i=0;i < iNumofStrings && szVersionInfo[i];i++) {
sprintf(szString,"\\StringFileInfo\\%04X%04X\\%s",Lang,CharSet,szVersionInfo[i]);
if (VerQueryValue(Buf,szString,&xBuf,(unsigned int *)&Size) != 0) {
if (Size >= iLenghtString) Size=iLenghtString-1;
strncpy(pVersionInfo+(i*iLenghtString),(char *)xBuf,Size);
(pVersionInfo+(i*iLenghtString))[Size]=0;
}
}
free(Buf);
return true;
}
/*
Function Description:
Get Filename from a process handle
Arguments:
IN hProc, Handle to process (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ)
OUT Buf, pointer to string containing filename after return, MAX_PATH in size
Returns:
true if succesfull
*/
bool HandleToName(HANDLE hProc,char *Buf)
{
if (!NtApi.fEnumProcessModules ||
!NtApi.fGetModuleFileNameEx
) {
return false;
}
HMODULE hModule;
DWORD dwSize;
if (NtApi.fEnumProcessModules(hProc, &hModule, sizeof(hModule), &dwSize)) {
if (NtApi.fGetModuleFileNameEx(hProc, hModule,Buf, MAX_PATH)) {
return true;
}
}
return false;
}
int GetPriority(DWORD dwPID,long BasePriority)
{
HANDLE hProc;
hProc = OpenProcess(PROCESS_QUERY_INFORMATION,false,dwPID);
DWORD dwPri=0;
if (hProc) {
dwPri = GetPriorityClass(hProc);
CloseHandle(hProc);
if (dwPri != 0) return dwPri;
}
if (BasePriority <= 4) return IDLE_PRIORITY_CLASS;
else if (BasePriority <= 6) return BELOW_NORMAL_PRIORITY_CLASS;
else if (BasePriority <= 8) return NORMAL_PRIORITY_CLASS;
else if (BasePriority <= 10) return ABOVE_NORMAL_PRIORITY_CLASS;
else if (BasePriority <= 13) return HIGH_PRIORITY_CLASS;
return REALTIME_PRIORITY_CLASS;
}
/*
Function Description:
Open file properties dialog
Arguments:
IN hWnd, Owner window
OUT szFileName, Name of the file to get properties from
Note: function calls GetFileName(szFileName) so after it returns
szFileName could be changed
Returns:
void
*/
void OpenFileProperties(HWND hWnd,char *szFileName)
{
SHELLEXECUTEINFO se;
memset((void*)&se,0,sizeof(SHELLEXECUTEINFO));
char *pFile;
pFile=GetFileName(szFileName);
se.cbSize = sizeof(SHELLEXECUTEINFO);
se.fMask = SEE_MASK_INVOKEIDLIST;
se.lpVerb = "properties";
se.lpFile = (char *)pFile;
se.nShow = SW_SHOW;
se.hwnd = hWnd;
ShellExecuteEx(&se);
}
/*
Function Description:
Set Debug and Shutdown privileges
Shows messagebox when it fails
Arguments:
Returns:
void
*/
void SetPrivileges()
{
HANDLE hToken=NULL;
LUID PrivNameValue;
TOKEN_PRIVILEGES Privileges;
DWORD dwRet;
if (OpenProcessToken(
GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
&hToken))
{
if (LookupPrivilegeValue(NULL,SE_DEBUG_NAME,&PrivNameValue)) {
Privileges.PrivilegeCount=1;
Privileges.Privileges[0].Luid=PrivNameValue;
Privileges.Privileges[0].Attributes=SE_PRIVILEGE_ENABLED;
if (!AdjustTokenPrivileges(hToken,FALSE,&Privileges,sizeof(Privileges),NULL,&dwRet) ||
GetLastError() == ERROR_NOT_ALL_ASSIGNED) {
ShowError(NULL,"Could not set %s privilege some option's may not work",SE_DEBUG_NAME);
}
}
if (LookupPrivilegeValue(NULL,SE_SHUTDOWN_NAME,&PrivNameValue)) {
Privileges.PrivilegeCount=1;
Privileges.Privileges[0].Luid=PrivNameValue;
Privileges.Privileges[0].Attributes=SE_PRIVILEGE_ENABLED;
if (!AdjustTokenPrivileges(hToken,FALSE,&Privileges,sizeof(Privileges),NULL,&dwRet) ||
GetLastError() == ERROR_NOT_ALL_ASSIGNED) {
ShowError(NULL,"Could not set %s privilege some option's may not work",SE_SHUTDOWN_NAME);
}
}
CloseHandle(hToken);
}
}
/*
Function Description:
Gets state of a popup menu item (Checked of unchecked)
Arguments:
IN hMenu, Handle to menu
IN iItem, menu item identifier
Returns:
true if state == MFS_CHECKED
false if state == MFS_UNCHECKED
*/
bool GetItemState(HMENU hMenu,int iItem)
{
MENUITEMINFO mii;
mii.cbSize=sizeof(mii);
mii.fMask=MIIM_STATE;
GetMenuItemInfo(hMenu,iItem,false,&mii);
return (mii.fState == MFS_CHECKED) ? true : false;
}
/*
Function Description:
Sets state of a popup menu item (Checked of unchecked)
Arguments:
IN hMenu, Handle to menu
IN iItem, menu item identifier
IN bChecked State to set (true for MFS_CHECKED else MFS_UNCHECKED)
Returns:
void
*/
void SetItemState(HMENU hMenu,int iItem,bool bChecked)
{
MENUITEMINFO mii;
mii.cbSize=sizeof(mii);
mii.fMask=MIIM_STATE;
mii.hbmpChecked=NULL;
mii.hbmpUnchecked=NULL;
if (bChecked) mii.fState = MFS_CHECKED;
else mii.fState = MFS_UNCHECKED;
SetMenuItemInfo(hMenu,iItem,false,&mii);
return;
}
/*
Function Description:
Shows error message (GetLastError())
Arguments:
IN dwError, Error message if NULL it calls GetLastError()
Returns:
void
*/
void DisplayError(DWORD dwError)
{
LPVOID lpBuffer;
int retValue;
//did the caller include a error message?
if (!dwError) dwError = GetLastError();
retValue = FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
dwError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&lpBuffer,
0,
NULL
);
if (retValue != 0) MessageBox(NULL,(char *)lpBuffer,"Error",0);
if (lpBuffer) LocalFree(lpBuffer);
return;
}
/*
Function Description:
retrieves the number of 100-nanoseconds that have elapsed since Windows was started.
Arguments:
Returns:
the return value is the number of 100-nanoseconds that have elapsed since Windows was started.
*/
ULONGLONG myNtGetTickCount()
{
if (!NtApi.fNtQuerySystemInformation) return NULL;
NTSTATUS ntStatus;
DWORD dwSize;
SYSTEM_TIME_OF_DAY_INFORMATION sti;
ntStatus = NtApi.fNtQuerySystemInformation(
SystemTimeOfDayInformation,
&sti,
sizeof(SYSTEM_TIME_OF_DAY_INFORMATION),
&dwSize
);
return (ULONGLONG)ntStatus == 0 ? sti.CurrentTime.QuadPart-sti.BootTime.QuadPart : 0;
}