Reputation: 947
I want to terminate one process, when I open this process, it built in my account and system.
Then I want to terminate this process using c++ program. My code could only terminate the process in my account, not in system. How could I change to terminate both?
My code is like:
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (Process32First(snapshot, &entry) == TRUE)
{
while (Process32Next(snapshot, &entry) == TRUE)
{
if (stricmp(entry.szExeFile, "tvnserver.exe") == 0)
{
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);
TerminateProcess(hProcess, 1);
CloseHandle(hProcess);
}
}
}
CloseHandle(snapshot);
Upvotes: 2
Views: 3261
Reputation: 131
Unless you have the required privileges to obtain a handle to the process, you can use the administrators special debug privileges to terminate the target process
Assuming you run as administrator you can enable the SE_DEBUG_NAME privilege on the current process, and you'll be able to terminate the target process. Alternatively could also take ownership of the target process as documented here https://social.msdn.microsoft.com/Forums/vstudio/en-US/3fb9cb5d-8891-4ba6-a945-06009be51e40/terminating-a-process-from-system-account-when-privileges-are-not-sufficient?forum=vcgeneral
This uses the first solution, and works for me, when running it as administrator.
#include <stdio.h>
#include <windows.h>
#include <TlHelp32.h>
NTSTATUS EnablePrivilege(wchar_t *privilege)
{
HANDLE token;
TOKEN_PRIVILEGES *tp = NULL;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token))
goto error;
tp = (TOKEN_PRIVILEGES*)new char[offsetof(TOKEN_PRIVILEGES, Privileges[1])];
if (!tp)
goto error;
tp->PrivilegeCount = 1;
tp->Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (!LookupPrivilegeValueW(0, privilege, &tp->Privileges[0].Luid))
goto error;
if (!AdjustTokenPrivileges(token, 0, tp, 0, 0, 0) || GetLastError() != ERROR_SUCCESS)
goto error;
CloseHandle(token);
return 0x0;
error:
if(tp)
delete[] tp;
return 0xC0000001;
}
int main()
{
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (Process32First(snapshot, &entry) == TRUE)
{
while (Process32Next(snapshot, &entry) == TRUE)
{
if (wcscmp(entry.szExeFile, L"spoolsv.exe") == 0)
{
NTSTATUS result = EnablePrivilege(SE_DEBUG_NAME);
if (result != 0)
{
printf("could not set SE_DEBUG_NAME Privilege\n");
getchar();
return -1;
}
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, entry.th32ProcessID);
if (hProcess == NULL)
{
printf("couldn't open process\n");
getchar();
return -1;
}
TerminateProcess(hProcess, 1);
CloseHandle(hProcess);
}
}
}
CloseHandle(snapshot);
printf("success!\n");
getchar();
return 0;
}
Upvotes: 3