Getting process name winapi - winapi

I have the problem , I can't get names of every process, some process show normal name but another return . How can I get the name of such process ? But the id is ok.
May I did something wrond , I am testing this on Windows 8.1
Here is the code .
DWORD aProcesses[1024], cbNeeded, cProcesses;
unsigned int i;
//This returns a list of handles to processes running on the system as an array.
if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) ) {
return 0;
}
// Calculate how many process identifiers were returned.
cProcesses = cbNeeded / sizeof(DWORD);
// Display the name and process identifier for each process.
for ( i = 0; i < cProcesses; i++ ) {
if( aProcesses[i] != 0 ) {
DisplayProcessNameAndID( aProcesses[i] );
}
}
void DisplayProcessNameAndID( DWORD processID )
{
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
// 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;
//Given a handle to a process, this returns all the modules running within the process.
//The first module is the executable running the process,
//and subsequent handles describe DLLs loaded into the process.
if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), &cbNeeded) )
{
//This function returns the short name for a module,
//typically the file name portion of the EXE or DLL
GetModuleBaseName( hProcess, hMod, szProcessName,
sizeof(szProcessName)/sizeof(TCHAR) );
}
}
// Display the process name and identifier.
char buffer[400];
sprintf_s(buffer,"Text:%s, PID : %u", szProcessName, processID );
MessageBox(mainWinH,buffer, "Ok", MB_OK);
//close the process handle
CloseHandle( hProcess );
}

Related

Find current PID and terminate him in kernel-mode

My file system minifilter driver for Windows 7x64 must denied access for some files. I`m get it, but associated application still work. I want to terminate process with this application. For example, when user try to open *.txt file, file and associated copy of notepad must be closed. I used example from WDK (Minispy) and functions ZwTerminateProcess and PsGetCurrentProcessId. Now, when user enter monitoring directory, my minifilter close explorer.exe. Example code:
minispy.c
...
NTSTATUS TermFunction( HANDLE ProcessID )
{
NTSTATUS ntStatus = STATUS_SUCCESS;
HANDLE hProcess;
OBJECT_ATTRIBUTES ObjectAttributes;
CLIENT_ID ClientId;
DbgPrint( "drvTerminateProcess( %u )", ProcessID );
InitializeObjectAttributes( &ObjectAttributes, NULL, OBJ_INHERIT, NULL, NULL );
ClientId.UniqueProcess = (HANDLE)ProcessID;
ClientId.UniqueThread = NULL;
__try
{
ntStatus = ZwOpenProcess( &hProcess, PROCESS_ALL_ACCESS, &ObjectAttributes, &ClientId );
if( NT_SUCCESS(ntStatus) )
{
ntStatus = ZwTerminateProcess( hProcess, 0 );
if( !NT_SUCCESS(ntStatus) )
DbgPrint( "ZwTerminateProcess failed with status : %08X\n", ntStatus );
ZwClose( hProcess );
}
else
DbgPrint( "ZwOpenProcess failed with status : %08X\n", ntStatus );
}
__except( EXCEPTION_EXECUTE_HANDLER )
{
ntStatus = STATUS_UNSUCCESSFUL;
DbgPrint( "Exception caught in drvTerminateProcess()" );
}
return ntStatus;
}
...
FLT_PREOP_CALLBACK_STATUS
SpyPreOperationCallback (
_Inout_ PFLT_CALLBACK_DATA Data,
_In_ PCFLT_RELATED_OBJECTS FltObjects,
_Flt_CompletionContext_Outptr_ PVOID *CompletionContext
)
{
UNICODE_STRING old_name;
PUNICODE_STRING new_old_name;
...
if (NT_SUCCESS( status )) {
nameToUse = &nameInfo->Name;
//
// Parse the name if requested
//
//Start of My func
RtlInitUnicodeString( &old_name, L"\\Device\\HarddiskVolume2\\secretfile.txt" );
new_old_name = &old_name;
if(RtlCompareUnicodeString(nameToUse, new_old_name, FALSE) == 0){
Data->IoStatus.Status = STATUS_ACCESS_DENIED;
TermFunction(PsGetCurrentProcessId);
return FLT_PREOP_COMPLETE;
}
...
}
....
}
Any idea?
(Excuse me if my English is bad)

Translating boost::thread->native_handle() to XP ThreadId

I've managed to get the Windows ThreadId out of the native_handle() from a boost::thread by using GetThreadId(HANDLE). Sadly that call is not available on Windows XP and after searching around I found the solution to offer als fallback support for XP by traversing all thread via Thread32First() and Thread32Next() functions of the WINAPI.
This does work somehow but my problem is I'm currently only able to identify the threads of my process... I don't now how to match the native_handle() / HANDLE from one side with the appropriate THREADENTRY32 from the loop traversal.
THREADENTRY32 te32;
//...
do {
if( te32.th32OwnerProcessID == GetCurrentProcessId() ) {
DWORD threadId = te32.th32ThreadID;
printf( "\n THREAD ID = 0x%08X", te32.th32ThreadID );
}
} while( Thread32Next(hThreadSnap, &te32 ) );
Can anyone help me with that? How do I convert a boost::thread->native_handle() to the ThreadId on WindowsXP?
Thank you very much!
Pass each thread ID in the loop to OpenThread() until you find a matching HANDLE. For example:
HANDLE hBoostThread = ...; // from boost::thread->native_handle()
DWORD dwBoostThreadID = 0;
THREADENTRY32 te32;
//...
do
{
if( te32.th32OwnerProcessID == GetCurrentProcessId() )
{
HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, te32.th32ThreadID);
if (hThread != NULL)
{
if (hThread == hBoostThread)
{
CloseHandle(hThread);
dwBoostThreadID = te32.th32ThreadID;
break;
}
CloseHandle(hThread);
}
}
}
while( Thread32Next(hThreadSnap, &te32 ) );
For good measure, you can wrap this inside a function that you can call whenever GetThreadId() is not natively available so that your code does not need to know the difference, eg:
DWORD WINAPI MyGetThreadId(HANDLE Thread)
{
THREADENTRY32 te32;
HANDLE hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (hThreadSnap == INVALID_HANDLE_VALUE)
return 0;
if (Thread32First(hThreadSnap, &te32))
{
do
{
HANDLE hOpenThread = OpenThread(THREAD_ALL_ACCESS, FALSE, te32.th32ThreadID);
if (hOpenThread != NULL)
{
if (hOpenThread == Thread)
{
CloseHandle(hOpenThread);
CloseHandle(hThreadSnap);
return te32.th32ThreadID;
}
CloseHandle(hOpenThread);
}
}
while( Thread32Next(hThreadSnap, &te32 ) );
}
CloseHandle(hThreadSnap);
return 0;
}
typedef DWORD (WINAPI *LPFN_GTID)(HANDLE);
LPFN_GTID lpGetThreadId = (LPFN_GTID) GetProcAddress(GetModuleHandle("kernel32"), "GetThreadId");
if (!lpGetThreadId)
lpGetThreadId = &MyGetThreadId;
DWORD dwThreadID = lpGetThreadId((HANDLE) boost::thread->native_handle());
With that said, a better option is to directly query the target thread itself for its own ID, instead of trying to hunt for it manually:
typedef long (WINAPI *LPFN_NTQIT)(HANDLE thread, int infoclass, void *buf, long size, long *used);
typedef struct _THREAD_BASIC_INFORMATION
{
ULONG ExitStatus;
void* TebBaseAddress;
ULONG UniqueProcessId;
ULONG UniqueThreadId;
ULONG AffinityMask;
ULONG BasePriority;
ULONG DiffProcessPriority;
} THREAD_BASIC_INFORMATION;
DWORD WINAPI MyGetThreadId(HANDLE Thread)
{
DWORD dwThreadId = 0;
HMODULE hLib = LoadLibrary("ntdll.dll");
if (hLib != NULL)
{
LPFN_NTQIT lpNtQueryInformationThread = (LPFN_NTQIT) GetProcAddress(hLib, "NtQueryInformationThread");
if (lpNtQueryInformationThread != NULL)
{
THREAD_BASIC_INFORMATION tbi = {0};
ULONG used = 0;
if (lpNtQueryInformationThread(Thread, 0, &tbi, sizeof(tbi), &used) == 0)
dwThreadId = tbi.UniqueThreadId;
}
FreeLibrary(hLib);
}
return dwThreadId;
}

Win32 C++ How to get current application Service Name

Assuming my code (DLL) already runs inside application that runs as service.
How to find the service name ?
I would like more elegant way than getting process path and enumerating services in registry.
I would suggest using GetCurrentProcessId to get the process ID of the service you're running in. Then use EnumServiceStatusEx to enumerate the services (without having to use the registry yourself).
You can match the process id from ENUM_SERVICE_STATUS_PROCESS.ServiceStatusProcess.dwProcessId to your current process ID and get the name. For example:
void enumerateServices( DWORD processId )
{
SC_HANDLE hSCM = OpenSCManager(NULL, NULL,
SC_MANAGER_ENUMERATE_SERVICE | SC_MANAGER_CONNECT);
if (hSCM == NULL)
{
return;
}
DWORD bufferSize = 0;
DWORD requiredBufferSize = 0;
DWORD totalServicesCount = 0;
EnumServicesStatusEx( hSCM,
SC_ENUM_PROCESS_INFO,
SERVICE_WIN32,
SERVICE_STATE_ALL,
nullptr,
bufferSize,
&requiredBufferSize,
&totalServicesCount,
nullptr,
nullptr );
std::vector<BYTE> buffer( requiredBufferSize );
EnumServicesStatusEx( hSCM,
SC_ENUM_PROCESS_INFO,
SERVICE_WIN32,
SERVICE_STATE_ALL,
buffer.data(),
buffer.size(),
&requiredBufferSize,
&totalServicesCount,
nullptr,
nullptr );
LPENUM_SERVICE_STATUS_PROCESS services =
reinterpret_cast<LPENUM_SERVICE_STATUS_PROCESS>( buffer.data() );
for ( unsigned int i = 0; i < totalServicesCount; ++i )
{
ENUM_SERVICE_STATUS_PROCESS service = services[i];
if ( service.ServiceStatusProcess.dwProcessId == processId )
{
// This is your service.
std::wcout << service.lpServiceName << L"PID: " <<
service.ServiceStatusProcess.dwProcessId << std::endl;
}
}
( void )CloseServiceHandle( hSCM );
}
Usual disclaimers about error handling apply. I've also not properly checked buffer sizes, etc.

DLL Injection: Calling a function inside the dll

First of all some parts of the code are from Calling function in injected DLL but somewhere it doesn't work.
I have a question regarding DLL Injection: after I loaded the library into another process:
HANDLE InjectDLL(DWORD ProcessID, char *dllName)
{
HANDLE Proc;
char buf[50]={0};
LPVOID RemoteString, LoadLibAddy;
if(!ProcessID)
return NULL;
Proc = OpenProcess(CREATE_THREAD_ACCESS, FALSE, ProcessID);
if(!Proc)
{
sprintf(buf, "OpenProcess() failed: %d", GetLastError());
MessageBox(NULL, buf, "Loader", NULL);
return NULL;
}
LoadLibAddy = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
RemoteString = (LPVOID)VirtualAllocEx(Proc, NULL, strlen(dllName), MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
WriteProcessMemory(Proc, (LPVOID)RemoteString, dllName, strlen(dllName), NULL);
HANDLE hThread = CreateRemoteThread(Proc, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibAddy, (LPVOID)RemoteString, NULL, NULL);
if( hThread != 0 ) {
WaitForSingleObject( hThread, INFINITE );
GetExitCodeThread( hThread, ( LPDWORD )&hInjected );
CloseHandle( hThread );
}
CloseHandle(Proc);
return hThread != 0 ? Proc : NULL;
}
I wanted to call a function from inside that space:
void* GetPayloadExportAddr( LPCSTR lpPath, HMODULE hPayloadBase, LPCSTR lpFunctionName )
{
// Load payload in our own virtual address space
HMODULE hLoaded = LoadLibrary( lpPath );
if( hLoaded == NULL ) {
return NULL;
} else {
void* lpFunc = GetProcAddress( hLoaded, lpFunctionName );
DWORD dwOffset = (char*)lpFunc - (char*)hLoaded;
FreeLibrary( hLoaded );
return (void*)((DWORD)hPayloadBase + dwOffset);
}
}
BOOL InitPayload( HANDLE hProcess, LPCSTR lpPath, HMODULE hPayloadBase)
{
void* lpInit = GetPayloadExportAddr( lpPath, hPayloadBase, "Start" );
if( lpInit == NULL ) {
return FALSE;
}
else {
HANDLE hThread = CreateRemoteThread( hProcess, NULL, 0,
(LPTHREAD_START_ROUTINE)lpInit, (LPVOID) NULL, 0, NULL );
if( hThread == NULL ) {
return FALSE;
}
else {
CloseHandle( hThread );
}
}
return TRUE;
}
The GetPayloadExportAddr returns the Current Location from IDA (i guess that is the space where my function starts).
So the problem is at the InitPayload function when I try to create the new thread, it fails to do so and I don't know why.
My dll is the following:
extern "C"
{
__declspec(dllexport) void* Start(LPVOID param)
{
MessageBox(NULL, L"Start", L"Hello", MB_OK);
return NULL;
}
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
The thing is if I put the Start method at DLL_PROCESS_ATTACH it works, but otherwise it doesn't.
Your GetPayloadExportAddr() returns the address of the function in your local process. This address will not be the same in other processes if the base address of the module is different, which is common with DLL files which can be relocated if their PreferredImageBase is not available.
You should modify your GetPayloadExportAddr() function to return the offset. Then get the address of the module in the target process. Add these two together and that is the correct address for you to call in the target process.

Why does DebugActiveProcessStop crash my debugging app?

I have a debugging program which I've written to attach to a process and create a crash dump file. That part works fine.
The problem I have is that when the debugger program terminates, so does the program that it was debugging.
I did some Googling and found the DebugActiveProcessStop() API call. This didn't show up in my older MSDN documentation as it was only introduced in Windows XP so I've tried loading it dynamicall from Kernel32.dll at runtime.
Now my problem is that my debugger program crashes as soon as the _DebugActiveProcessStop() call is made. Can somebody please tell me what I'm doing wrong?
typedef BOOL (*DEBUGACTIVEPROCESSSTOP)(DWORD);
DEBUGACTIVEPROCESSSTOP _DebugActiveProcessStop;
HMODULE hK32 = LoadLibrary( "kernel32.dll" );
if( hK32 )
_DebugActiveProcessStop = (DEBUGACTIVEPROCESSSTOP) GetProcAddress( hK32,"DebugActiveProcessStop" );
else
{
printf( "Can't load Kernel32.dll\n" );
return;
}
if( ! _DebugActiveProcessStop )
{
printf( "Can't find DebugActiveProcessStop\n" );
return;
}
...
void DebugLoop( void )
{
DEBUG_EVENT de;
while( 1 )
{
WaitForDebugEvent( &de, INFINITE );
switch( de.dwDebugEventCode )
{
case CREATE_PROCESS_DEBUG_EVENT:
hProcess = de.u.CreateProcessInfo.hProcess;
break;
case EXCEPTION_DEBUG_EVENT:
// PDS: I want a crash dump immediately!
dwProcessId = de.dwProcessId;
dwThreadId = de.dwThreadId;
WriteCrashDump( &de.u.Exception );
return;
case CREATE_THREAD_DEBUG_EVENT:
case OUTPUT_DEBUG_STRING_EVENT:
case EXIT_THREAD_DEBUG_EVENT:
case EXIT_PROCESS_DEBUG_EVENT :
case LOAD_DLL_DEBUG_EVENT:
case UNLOAD_DLL_DEBUG_EVENT:
case RIP_EVENT:
default:
break;
}
ContinueDebugEvent( de.dwProcessId, de.dwThreadId, DBG_CONTINUE );
}
}
...
void main( void )
{
...
BOOL bo = DebugActiveProcess( dwProcessId );
if( bo == 0 )
printf( "DebugActiveProcess failed, GetLastError: %u \n",GetLastError() );
hProcess = OpenProcess( PROCESS_ALL_ACCESS, TRUE, dwProcessId );
if( hProcess == NULL )
printf( "OpenProcess failed, GetLastError: %u \n",GetLastError() );
DebugLoop();
_DebugActiveProcessStop( dwProcessId );
CloseHandle( hProcess );
}
The reason its crashing is because I missed out the WINAPI keyword on my function pointer definitions.
This works:
typedef BOOL (WINAPI *DEBUGSETPROCESSKILLONEXIT)(BOOL);

Resources