i'm using QT to check if process is running and i used the same code in msdn site.
It worked fine on Visual Studio but i'm having a problem making it work on QT.
Here's the code :
bool matchProcessName( DWORD processID, std::string processName)
{
TCHAR szProcessName[MAX_PATH] = TEXT(L"notepad.exe");
// Get a handle to the process.
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ,
FALSE, processID );
// Get the process name.
if (NULL != hProcess )
{
HMODULE hMod;
DWORD cbNeeded;
if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod),
&cbNeeded) )
{
GetModuleBaseName( hProcess, hMod, szProcessName,
sizeof(szProcessName)/sizeof(TCHAR) );
}
}
// Compare process name with your string
bool matchFound = !_tcscmp(szProcessName, processName.c_str() );
// Release the handle to the process.
CloseHandle( hProcess );
return matchFound;
}
The Error i'm getting is this :
error: cannot convert 'TCHAR*' to 'const char*' for argument '1' to 'int strcmp(const char*, const char*)'
How can i make this work on QT ?
Thanks alot.
Update
I also tried this code :
DWORD FindProcessId(char* processName)
{
char* p = strrchr(processName, '\\');
if(p)
processName = p+1;
PROCESSENTRY32 processInfo;
processInfo.dwSize = sizeof(processInfo);
HANDLE processesSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if ( processesSnapshot == INVALID_HANDLE_VALUE )
return 0;
Process32First(processesSnapshot, &processInfo);
if ( !strcmp(processName, processInfo.szExeFile) )
{
CloseHandle(processesSnapshot);
return processInfo.th32ProcessID;
}
while ( Process32Next(processesSnapshot, &processInfo) )
{
if ( !strcmp(processName, processInfo.szExeFile) )
{
CloseHandle(processesSnapshot);
return processInfo.th32ProcessID;
}
}
CloseHandle(processesSnapshot);
return 0;
}
I'm also getting an error :cannot convert 'WCHAR*' to 'const char*' for argument '2' to 'int strcmp(const char*, const char*)'
I prefer if i can make 2nd method work !
Thanks again
It has nothing to do with Qt.
In the updated code, PROCESSENTRY32.szExeFile is a TCHAR[],
i.e. it is a WCHAR[] if the macro _UNCODE is defined else is a char[].
So you have to transfer your char *processName to TCHAR[] and use _tcscmp(...) to compare TCHAR[].
Modified code:
#include <Windows.h>
#include <TlHelp32.h>
#include <tchar.h>
#include <Psapi.h>
#include <cstring>
#include <string>
#define MIN(x, y) ((x) > (y)) ? (y) : (x)
void cstringToTCHAR(TCHAR *dst, const char *src, size_t l) {
#if defined(_UNICODE) || defined(UNICODE
mbstowcs(dst, src, l);
#else
memcpy(dst, src, l);
#endif
}
bool matchProcessName( DWORD processID, std::string processName)
{
TCHAR szProcessName[MAX_PATH] = _T("notepad.exe");
// Get a handle to the process.
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ,
FALSE, processID );
// Get the process name.
if (NULL != hProcess )
{
HMODULE hMod;
DWORD cbNeeded;
if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod),
&cbNeeded) )
{
GetModuleBaseName( hProcess, hMod, szProcessName,
sizeof(szProcessName)/sizeof(TCHAR) );
}
}
// Compare process name with your string
TCHAR systemEncodeProcessName[30];
size_t processNameLen = MIN((processName.size() + 1), 30);
cstringToTCHAR(systemEncodeProcessName, processName.c_str(), processNameLen);
bool matchFound = !_tcscmp(szProcessName, systemEncodeProcessName);
// Release the handle to the process.
CloseHandle( hProcess );
return matchFound;
}
DWORD FindProcessId(char* processName) {
char* p = strrchr(processName, '\\');
if(p) {
processName = p+1;
}
PROCESSENTRY32 processInfo;
processInfo.dwSize = sizeof(processInfo);
HANDLE processesSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (processesSnapshot == INVALID_HANDLE_VALUE) {
return 0;
}
//Transfer char array to TCHAR array.
TCHAR systemEncodeProcessName[30];//Maybe need more or dynamic allocation.
size_t processNameLen = MIN((strlen(processName) + 1), 30);
cstringToTCHAR(systemEncodeProcessName, processName, processNameLen);
Process32First(processesSnapshot, &processInfo);
if (!_tcscmp(systemEncodeProcessName, processInfo.szExeFile)) {
CloseHandle(processesSnapshot);
return processInfo.th32ProcessID;
}
while ( Process32Next(processesSnapshot, &processInfo) ) {
if ( !_tcscmp(systemEncodeProcessName, processInfo.szExeFile) ) {
CloseHandle(processesSnapshot);
return processInfo.th32ProcessID;
}
}
CloseHandle(processesSnapshot);
return 0;
}
Update
In Qt creator(3.3.0), the _UNICODE macro looks like missing in Windows platform, just add
DEFINES += _UNICODE
in your .pro file and then run qmake && build.
Related
Well, basically I need to write a DLL in C++ that I will inject into notepad.exe.
This DLL suppose to open a pop-out message or a window with my name in it.
The problem is that I'm kinda new with DLL and I started a week ago. I'm having trouble opening a window or a message with a DLL using "windows.h".
I did try using MessageBox but it's not working.
that's my injector
that i took from: https://www.fxp.co.il/showthread.php?t=15051062
#include <iostream>
#include <direct.h>
#include <windows.h>
#include <Tlhelp32.h>
LPCTSTR SzToLPCTSTR(char* szString);
char* GetCurrentDir();
void WaitForProcessToAppear(LPCTSTR lpcszProc, DWORD dwDeley);
DWORD GetProcessIdByName(LPCTSTR lpcszProc);
BOOL InjectDll(DWORD dwPid, char* szDllPath);
int main()
{
char szProc[MAX_PATH], szDll[MAX_PATH];
char* szDllPath = (char*)malloc(MAX_PATH);
LPTSTR lpszProc = NULL;
while (true)
{
std::cout << "Process: ";
std::cin >> szProc;
std::cout << "DLL Injection: ";
std::cin >> szDll;
szDllPath = GetCurrentDir();
strcat_s(szDllPath, MAX_PATH, "\\");
strcat_s(szDllPath, MAX_PATH, szDll);
std::cout << "Waiting for process..." << std::endl;
WaitForProcessToAppear(SzToLPCTSTR(szProc), 100);
if (InjectDll(GetProcessIdByName(SzToLPCTSTR(szProc)), szDllPath)) std::cout << "Injection succeeded!" << std::endl;
else std::cout << "Injection failed!" << std::endl;
std::cout << "\n";
}
return 0;
}
char* GetCurrentDir()
{
char* szRet = (char*)malloc(MAX_PATH);
_getcwd(szRet, MAX_PATH);
return szRet;
}
LPCTSTR SzToLPCTSTR(char* szString)
{
LPTSTR lpszRet;
size_t size = strlen(szString) + 1;
lpszRet = (LPTSTR)malloc(MAX_PATH);
mbstowcs_s(NULL, lpszRet, size, szString, _TRUNCATE);
return lpszRet;
}
void WaitForProcessToAppear(LPCTSTR lpcszProc, DWORD dwDeley)
{
HANDLE hSnap;
PROCESSENTRY32 peProc;
BOOL bAppeared = FALSE;
while (!bAppeared)
{
if ((hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)) != INVALID_HANDLE_VALUE)
{
peProc.dwSize = sizeof(PROCESSENTRY32);
if (Process32First(hSnap, &peProc))
while (Process32Next(hSnap, &peProc) && !bAppeared)
if (!lstrcmp(lpcszProc, peProc.szExeFile))
bAppeared = TRUE;
}
CloseHandle(hSnap);
Sleep(dwDeley);
}
}
DWORD GetProcessIdByName(LPCTSTR lpcszProc)
{
HANDLE hSnap;
PROCESSENTRY32 peProc;
DWORD dwRet = -1;
if ((hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)) != INVALID_HANDLE_VALUE)
{
peProc.dwSize = sizeof(PROCESSENTRY32);
if (Process32First(hSnap, &peProc))
while (Process32Next(hSnap, &peProc))
if (!lstrcmp(lpcszProc, peProc.szExeFile))
dwRet = peProc.th32ProcessID;
}
CloseHandle(hSnap);
return dwRet;
}
BOOL InjectDll(DWORD dwPid, char* szDllPath)
{
DWORD dwMemSize;
HANDLE hProc;
LPVOID lpRemoteMem, lpLoadLibrary;
BOOL bRet = FALSE;
if ((hProc = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_CREATE_THREAD, FALSE, dwPid)) != NULL)
{
dwMemSize = strlen(szDllPath) + 1;
if ((lpRemoteMem = VirtualAllocEx(hProc, NULL, dwMemSize, MEM_COMMIT, PAGE_READWRITE)) != NULL)
if (WriteProcessMemory(hProc, lpRemoteMem, (LPCVOID)szDllPath, dwMemSize, NULL))
{
lpLoadLibrary = GetProcAddress(GetModuleHandleA("kernel32.dll"), "LoadLibraryA");
if (CreateRemoteThread(hProc, NULL, 0, (LPTHREAD_START_ROUTINE)lpLoadLibrary, lpRemoteMem, 0, NULL) != NULL)
bRet = TRUE;
}
}
CloseHandle(hProc);
return bRet;
}
And that's my DLL:
#include <windows.h>
BOOL WINAPI DllMain( HMODULE hModule,
DWORD fdwReason,
LPVOID lpvReserved
)
{
if (fdwReason == DLL_PROCESS_ATTACH)
MessageBox(NULL, L"Injected by Matan Oshri", L"Hello World", MB_OK);
return TRUE;
}
Please let me know if u see any kind of mistake.
I appreciate all the help I can get.
Thank you.
First I can inject the DLL with the sample code, make sure the Dll, injector.exe and notepad.exe are in the same bits(Usually, notepad.exe starts with 64-bit).
I am getting the error code = 5 if I use 32-bits of DLL or injector.exe with 64-bits notepad.exe
Second, According to the CreateRemoteThread document:
hProcess
A handle to the process in which the thread is to be created. The
handle must have the PROCESS_CREATE_THREAD, PROCESS_QUERY_INFORMATION,
PROCESS_VM_OPERATION, PROCESS_VM_WRITE, and PROCESS_VM_READ access
rights, and may fail without these rights on certain platforms. For
more information, see Process Security and Access Rights.
(Although the above sample works for me with out PROCESS_QUERY_INFORMATION and PROCESS_VM_READ)
Third, There is something worth improving in your code:
char* szDllPath = (char*)malloc(MAX_PATH);
szDllPath = GetCurrentDir();
/*{
char* szRet = (char*)malloc(MAX_PATH);
_getcwd(szRet, MAX_PATH);
return szRet;
}*/
This will cause the memory of the first application to be leaked.
LPCTSTR SzToLPCTSTR(char* szString);
We could use Unicode string directly.
sample:
#include <iostream>
#include <direct.h>
#include <windows.h>
#include <Tlhelp32.h>
//LPCWSTR SzToLPCTSTR(char* szString);
//char* GetCurrentDir();
void WaitForProcessToAppear(LPCWSTR lpcszProc, DWORD dwDeley);
DWORD GetProcessIdByName(LPCWSTR lpcszProc);
BOOL InjectDll(DWORD dwPid, LPCWSTR szDllPath);
int main()
{
while (true)
{
std::wstring szProc, szDll;
std::wstring szDllPath;
std::wcout << L"Process: ";
std::wcin >> szProc;
std::wcout << L"DLL Injection: ";
std::wcin >> szDll;
WCHAR dir[MAX_PATH] = { 0 };
GetCurrentDirectoryW(MAX_PATH, dir);
szDllPath = dir;
szDllPath += L"\\";
szDllPath += szDll;
std::wcout << L"Waiting for process..." << std::endl;
WaitForProcessToAppear(szProc.c_str(), 100);
if (InjectDll(GetProcessIdByName(szProc.c_str()), szDllPath.c_str())) std::wcout << L"Injection succeeded!" << std::endl;
else std::wcout << L"Injection failed!" << std::endl;
std::wcout << L"\n";
}
return 0;
}
//char* GetCurrentDir()
//{
// char* szRet = (char*)malloc(MAX_PATH);
// _getcwd(szRet, MAX_PATH);
// return szRet;
//}
//LPCWSTR SzToLPCTSTR(char* szString)
//{
// LPTSTR lpszRet;
// size_t size = strlen(szString) + 1;
// lpszRet = (LPTSTR)malloc(MAX_PATH);
// mbstowcs_s(NULL, lpszRet, size, szString, _TRUNCATE);
// return lpszRet;
//}
void WaitForProcessToAppear(LPCWSTR lpcszProc, DWORD dwDeley)
{
HANDLE hSnap;
PROCESSENTRY32 peProc;
BOOL bAppeared = FALSE;
while (!bAppeared)
{
if ((hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)) != INVALID_HANDLE_VALUE)
{
peProc.dwSize = sizeof(PROCESSENTRY32);
if (Process32First(hSnap, &peProc))
while (Process32Next(hSnap, &peProc) && !bAppeared)
if (!lstrcmp(lpcszProc, peProc.szExeFile))
{
bAppeared = TRUE;
break;
}
}
CloseHandle(hSnap);
Sleep(dwDeley);
}
}
DWORD GetProcessIdByName(LPCWSTR lpcszProc)
{
HANDLE hSnap;
PROCESSENTRY32 peProc;
DWORD dwRet = -1;
if ((hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)) != INVALID_HANDLE_VALUE)
{
peProc.dwSize = sizeof(PROCESSENTRY32);
if (Process32First(hSnap, &peProc))
while (Process32Next(hSnap, &peProc))
if (!lstrcmp(lpcszProc, peProc.szExeFile))
{
dwRet = peProc.th32ProcessID;
break;
}
}
CloseHandle(hSnap);
return dwRet;
}
BOOL InjectDll(DWORD dwPid, LPCWSTR szDllPath)
{
DWORD dwMemSize;
HANDLE hProc;
LPVOID lpRemoteMem, lpLoadLibrary;
BOOL bRet = FALSE;
if ((hProc = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, dwPid)) != NULL)
{
dwMemSize = (wcslen(szDllPath) + 1) * sizeof(WCHAR);
if ((lpRemoteMem = VirtualAllocEx(hProc, NULL, dwMemSize, MEM_COMMIT, PAGE_READWRITE)) != NULL)
if (WriteProcessMemory(hProc, lpRemoteMem, (LPCVOID)szDllPath, dwMemSize, NULL))
{
lpLoadLibrary = GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "LoadLibraryW");
if (CreateRemoteThread(hProc, NULL, 0, (LPTHREAD_START_ROUTINE)lpLoadLibrary, lpRemoteMem, 0, NULL) != NULL)
bRet = TRUE;
}
}
CloseHandle(hProc);
return bRet;
}
Finally, according to the limitations in DllMain:
Call functions in User32.dll or Gdi32.dll. Some functions load
another DLL, which may not be initialized.
You cannot use MessageBox in DllMain, but you could use OutputDebugStringW instead to show a message, and use DebugView to check the debug string.
DLL:
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
OutputDebugStringW(L"Injected DLL_PROCESS_ATTACH by Matan Oshri");
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
Or use Console API to pop up a console:
DWORD dwSize;
WCHAR string[] = L"Hello World";
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
AllocConsole();
WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), string, 12, &dwSize, NULL);
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
i have written a method to get all process id's inside a c++ project.
Int CProcessHelper::GetAllPIDs(const char *processName, _STL_NAMESPACE_::vector<DWORD> &pids)
{
HANDLE hProcessSnap;
PROCESSENTRY32 pe32;
HANDLE hProcess;
BOOL bContinue;
pids.clear();
// Take a snapshot of all processes in the system.
hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
if( hProcessSnap == INVALID_HANDLE_VALUE )
{
return 0;
}
// Set the size of the structure before using it.
pe32.dwSize = sizeof( PROCESSENTRY32 );
// Retrieve information about the first process,
// and exit if unsuccessful
bContinue = Process32First( hProcessSnap, &pe32 );
while(bContinue)
{
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ, FALSE, pe32.th32ProcessID);
if( hProcess != NULL )
{
TCHAR szModName[MAX_PATH];
// Get the full path to the module's file.
if(GetModuleFileNameEx( hProcess, NULL, szModName,
sizeof(szModName)))
{
char *ptr = strrchr(szModName, '\\');
if( (ptr && stricmp(ptr+1, processName) == 0) ||
stricmp(szModName, processName) == 0)
{
pids.push_back(pe32.th32ProcessID);
/*CloseHandle( hProcess );
pid = pe32.th32ProcessID;
break;*/
}
}
CloseHandle( hProcess );
}
bContinue = Process32Next( hProcessSnap, &pe32 );
}
CloseHandle( hProcessSnap );
return (int) pids.size();
}
When i run this code under Dr Memory, i am getting following "Uninitialized Read" errors:
Uninitialized Read Error 1
at this line:
if(GetModuleFileNameEx( hProcess, NULL, szModName,
sizeof(szModName)))
2nd error is :
Uninitialized Read Error 2
at this line -
bContinue = Process32First( hProcessSnap, &pe32 );
i am not getting by Dr Memory reporting me these errors. Are these only false positive errors?
Please help me to identify which part is uninitialized here.
If you look at the attached Dr Memory error screenshot carefully, you will notice that both the errors have call to the
KERNELBASE.dll!WideCharToMultiByte
Since i am using TCHAR(1.e of char type, rather then of WCHAR type(wide char)) for szFileName var.
TCHAR szModName[MAX_PATH];
I am not getting why it is calling WideCharToMultiByte() method as i am using a method which accept char type rather then a wide char type.
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pe32.th32ProcessID);
pe32.th32ProcessID is not set yet, it's uninitialized memory. OpenProcess() is also not needed for your purpose.
if (GetModuleFileNameEx(hProcess, NULL, szModName, sizeof(szModName)))
this function is unnecessary, the executable name is exposed by the PROCESSENTRY32 structure. In addition, the last argument should use strlen, not sizeof because you want number of characters not size of buffer.
There are other issues with this code as well, rather than trying to reinvent the wheel, MSDN has a complete commented source code for doing what you want to do using the ToolHelp32Snapshot collection of functions, you can find it here.
Here is a concise example I have modified to fit your needs without any problems:
#include <windows.h>
#include <iostream>
#include <vector>
#include <TlHelp32.h>
#include <Psapi.h>
int GetAllPIDs(const char* processName, std::vector<DWORD>& pids)
{
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnap != INVALID_HANDLE_VALUE)
{
PROCESSENTRY32 procEntry;
procEntry.dwSize = sizeof(procEntry);
if (Process32First(hSnap, &procEntry))
{
do
{
if (!_stricmp(procEntry.szExeFile, processName))
{
pids.push_back(procEntry.th32ProcessID);
}
} while (Process32Next(hSnap, &procEntry));
}
}
CloseHandle(hSnap);
return (int)pids.size();
}
int main()
{
std::vector<DWORD> piddies;
GetAllPIDs("calc.exe", piddies);
for (auto p : piddies)
{
std::cout << "0x" << std::hex << p << std::endl;
}
std::getchar();
return 0;
}
We have an application that has 3 processes as shown in the image below.
What I wanted to do is to terminate these processes. After reading a few tutorials, I was able to collate these codes. However, it's not working properly. The output is shown after the code.
HANDLE hProcessSnap;
PROCESSENTRY32 pe32;
hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
pe32.dwSize = sizeof( PROCESSENTRY32 );
std::string message = "";
int processCounter = 0;
while( Process32Next( hProcessSnap, &pe32 ) ) {
char ch[260];
char DefChar = ' ';
WideCharToMultiByte(CP_ACP,0,pe32.szExeFile,-1, ch,260,&DefChar, NULL);
//A std:string using the char* constructor.
std::string process(ch);
if( process == "bridge.exe" ) {
std::wstring stemp = std::wstring(process.begin(), process.end());
LPCWSTR sw = stemp.c_str();
HWND windowHandle = FindWindowW( NULL, sw );
DWORD* dwProcessId = new DWORD;
GetWindowThreadProcessId( windowHandle, dwProcessId );
message.append( process );
message.append( "-" );
std::ostringstream converter;
converter << *dwProcessId;
message.append( converter.str() );
message.append( "-" );
DWORD dwDesiredAccess = PROCESS_TERMINATE;
BOOL bInheritHandle = FALSE;
HANDLE hProcess = OpenProcess(dwDesiredAccess, bInheritHandle, *dwProcessId);
if( hProcess == NULL ) {
BOOL result = TerminateProcess(hProcess, 0);
message.append( "NULL" );
}
message.append( "\n" );
CloseHandle(hProcess);
}
}
This is the output:
bridge.exe-4597928-NULL
bridge.exe-4597568-NULL
bridge.exe-4587524-NULL
hProcess returns NULL. What did I miss? Thanks.
When I was trying to use Detours in order to hook CreateFile, when my hooked function is called I get a stack overflow error. I am trying to write the filename to a file and then call the original, but it fails on the fopen call with a stack overflow error. I am injecting the dll via CreateRemoteThread call. Is there some special stack allocation we have to do in the target process. I am fairly new to Windows development and detours, but I know C/C++ fairly well but by no means an expert.
#include "stdafx.h"
#include "detours.h"
#include <cstdio>
#include <ws2tcpip.h>
#include <windows.h>
#include <stdio.h>
#pragma comment(lib, "detours.lib")
//#pragma comment(lib, "detoured.lib")
#pragma comment(lib, "ws2_32.lib")
HANDLE (WINAPI *oldCreate)(LPCTSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD,DWORD, HANDLE ) = CreateFile;
HANDLE WINAPI myCreate(LPCTSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD,DWORD,HANDLE);
INT APIENTRY DllMain(HMODULE hDLL, DWORD Reason, LPVOID Reserved)
{
switch(Reason)
{
case DLL_PROCESS_ATTACH:
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&)oldCreate, myCreate);
DetourTransactionCommit();
break;
case DLL_PROCESS_DETACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
break;
}
return TRUE;
}
HANDLE WINAPI myCreate(LPCTSTR lpFileName , DWORD dwDesiredAccess, DWORD dwShareMode , LPSECURITY_ATTRIBUTES lpSecurityAttributes , DWORD dwCreationDisposition ,DWORD dwFlagsAndAttributes, HANDLE hTemplateFile)
{
int x= 3;
FILE *file = fopen("C:\\test.txt", "a+");
fprintf(file, "%s \n", lpFileName);
fclose(file);
return oldCreate(lpFileName,dwDesiredAccess,dwShareMode,lpSecurityAttributes,dwCreationDisposition,dwFlagsAndAttributes,hTemplateFile);
}
extern "C" __declspec(dllexport) void dummy(void){`enter code here`
return;
}
Here is the injector Code I am using
Also, here is the injector code I am using
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include "detours.h"
#pragma comment (lib, "detours.lib")
#define MAX_COMBINED 8192
BOOL SetPrivilege(
HANDLE hToken, // token handle
LPCTSTR Privilege, // Privilege to enable/disable
BOOL bEnablePrivilege // TRUE to enable. FALSE to disable
);
LPTSTR GetArguments(void)
{
LPWSTR *szArglist = NULL;
int nArgs;
LPWSTR wbuf = NULL;
wbuf = new WCHAR[MAX_COMBINED];
if (wbuf == NULL)
return NULL;
memset(wbuf, 0, MAX_COMBINED*sizeof(WCHAR));
szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
if(NULL == szArglist)
{
return NULL;
}
else {
for(int i=2; i<nArgs; i++) {
wcscat_s(wbuf, MAX_COMBINED, szArglist[i]);
wcscat_s(wbuf, MAX_COMBINED, L" ");
}
}
LocalFree(szArglist);
#ifdef _UNICODE
return wbuf;
#else
LPSTR abuf = new CHAR[MAX_COMBINED];
if (abuf == NULL)
return NULL;
memset(abuf, 0, MAX_COMBINED);
WideCharToMultiByte(CP_ACP, 0, wbuf, -1, abuf, MAX_COMBINED, NULL, NULL);
delete[] wbuf;
return abuf;
#endif
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hToken;
if(argc < 2)
{
printf("pass just pid]\n");
return 0;
}
char* DirPath = new char[MAX_PATH];
char* FullPath = new char[MAX_PATH];
GetCurrentDirectoryA(MAX_PATH, (LPSTR)DirPath);
sprintf_s(FullPath, MAX_PATH, "%s\\injector3.dll", DirPath);
printf("FullPath %s \n",FullPath);
if(!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &hToken))
{
if (GetLastError() == ERROR_NO_TOKEN)
{
if (!ImpersonateSelf(SecurityImpersonation))
return 1;
if(!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &hToken)){
printf("OpenThreadToken\n");
return 1;
}
}
else
return 1;
}
// enable SeDebugPrivilege
if(!SetPrivilege(hToken, SE_DEBUG_NAME, TRUE))
{
printf("SetPrivilege");
// close token handle
CloseHandle(hToken);
// indicate failure
return 2;
}
HANDLE hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION |
PROCESS_VM_WRITE, FALSE, _wtoi(argv[1]));
if(hProcess == NULL)
{
DWORD x = GetLastError();
printf("HANDLE TO PROCESS FAILED on PID %d with error %d\n",_wtoi(argv[1]),x);
return 1;
}
LPVOID LoadLibraryAddr = (LPVOID)GetProcAddress(GetModuleHandleA("kernel32.dll"),
"LoadLibraryA");
if(LoadLibraryAddr == NULL)
{
printf("GET PROC ADDRESS FAILED on PID %s\n",argv[1]);
return 1;
}
LPVOID LLParam = (LPVOID)VirtualAllocEx(hProcess, NULL, strlen(FullPath),
MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if(LLParam == NULL)
{
printf("VirtualAllocEx on PID %s\n",argv[1]);
return 1;
}
WriteProcessMemory(hProcess, LLParam, FullPath, strlen(FullPath), NULL);
CreateRemoteThread(hProcess, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibraryAddr,
LLParam, NULL, NULL);
CloseHandle(hProcess);
delete [] DirPath;
delete [] FullPath;
}
BOOL SetPrivilege(
HANDLE hToken, // token handle
LPCTSTR Privilege, // Privilege to enable/disable
BOOL bEnablePrivilege // TRUE to enable. FALSE to disable
)
{
TOKEN_PRIVILEGES tp;
LUID luid;
TOKEN_PRIVILEGES tpPrevious;
DWORD cbPrevious=sizeof(TOKEN_PRIVILEGES);
if(!LookupPrivilegeValue( NULL, Privilege, &luid )) return FALSE;
//
// first pass. get current privilege setting
//
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = 0;
AdjustTokenPrivileges(
hToken,
FALSE,
&tp,
sizeof(TOKEN_PRIVILEGES),
&tpPrevious,
&cbPrevious
);
if (GetLastError() != ERROR_SUCCESS) return FALSE;
//
// second pass. set privilege based on previous setting
//
tpPrevious.PrivilegeCount = 1;
tpPrevious.Privileges[0].Luid = luid;
if(bEnablePrivilege) {
tpPrevious.Privileges[0].Attributes |= (SE_PRIVILEGE_ENABLED);
}
else {
tpPrevious.Privileges[0].Attributes ^= (SE_PRIVILEGE_ENABLED &
tpPrevious.Privileges[0].Attributes);
}
AdjustTokenPrivileges(
hToken,
FALSE,
&tpPrevious,
cbPrevious,
NULL,
NULL
);
if (GetLastError() != ERROR_SUCCESS) return FALSE;
return TRUE;
}
/*
BOOL SetPrivilege(
HANDLE hToken, // token handle
LPCTSTR Privilege, // Privilege to enable/disable
BOOL bEnablePrivilege // TRUE to enable. FALSE to disable
)
{
TOKEN_PRIVILEGES tp = { 0 };
// Initialize everything to zero
LUID luid;
DWORD cb=sizeof(TOKEN_PRIVILEGES);
if(!LookupPrivilegeValue( NULL, Privilege, &luid ))
return FALSE;
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
if(bEnablePrivilege) {
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
} else {
tp.Privileges[0].Attributes = 0;
}
AdjustTokenPrivileges( hToken, FALSE, &tp, cb, NULL, NULL );
if (GetLastError() != ERROR_SUCCESS)
return FALSE;
return TRUE;
}
*/
You are replacing CreateFile with your myCreate.
When fopen calls CreateFile to open the file, it will instead call your myCreate again, which will call fopen, which will call CreateFile and so on until you run out of stack.
You could call oldCreateFile to open the file for outputting, but you won't be able to use fprintf etc with it.
In Visual C++, am getting the title of the current window using
::GetWindowText(wnd, str, 290);
strcpy(curr_wnd_txt, str);
But how can i get the Process Name of the Application for example "Iexplore" for Using Internet Explorer, "Skype" for window with tile "Skype - username", "Explorer" for using windows explorer ?
This is what i tried :
void CMainWndDlg::Monitor_ActiveWindowCaptions()
{
HWND hwnd;
DWORD process_id=0;
GetWindowThreadProcessId(hwnd, &process_id);
CString strEXEName = GetEXEName (process_id);
}
CString GetEXEName(DWORD dwProcessID)
{
DWORD aProcesses [1024], cbNeeded, cProcesses;
unsigned int i;
if (!EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded))
return "";
cProcesses = cbNeeded / sizeof(DWORD);
TCHAR szEXEName[MAX_PATH];
for (i = 0; i < cProcesses; i++)
{
if (aProcesses [i] == dwProcessID)
{
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ, FALSE, dwProcessID);
if (NULL != hProcess)
{
HMODULE hMod;
DWORD cbNeeded;
if(EnumProcessModules(hProcess, &hMod,
sizeof(hMod), &cbNeeded))
{
GetModuleBaseName(hProcess, hMod, szEXEName,
sizeof(szEXEName)/sizeof(TCHAR));
return CString (szEXEName);
}
}
}
}
return "";
}
GetModuleFileName() can be used to retrieve the path of the executable file of the current process.
http://msdn.microsoft.com/en-gb/library/windows/desktop/ms683197(v=vs.85).aspx
You will have to enumerate the windows, get the process handle, and then get the name of the executable from the function below.
#include "psapi.h"
#pragma comment(lib, "psapi.lib")
CString GetEXEName(DWORD dwProcessID)
{
DWORD aProcesses [1024], cbNeeded, cProcesses;
unsigned int i;
//Enumerate all processes
if (!EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded))
return NULL;
// Calculate how many process identifiers were returned.
cProcesses = cbNeeded / sizeof(DWORD);
TCHAR szEXEName[MAX_PATH];
//Loop through all process to find the one that matches
//the one we are looking for
for (i = 0; i < cProcesses; i++)
{
if (aProcesses [i] == dwProcessID)
{
// Get a handle to the process
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ, FALSE, dwProcessID);
// Get the process name
if (NULL != hProcess)
{
HMODULE hMod;
DWORD cbNeeded;
if(EnumProcessModules(hProcess, &hMod,
sizeof(hMod), &cbNeeded))
{
//Get the name of the exe file
GetModuleBaseName(hProcess, hMod, szEXEName,
sizeof(szEXEName)/sizeof(TCHAR));
return CString (szEXEName);
}
}
}
}
return NULL;
}
Refer here: http://www.codeproject.com/Articles/14843/Finding-module-name-from-the-window-handle