SeDebugPrivilege issue on Windows 8.1 and windows 10 - c++

a few days ago I posted a question about ReadProcessMemory not returning the correct value, now I been aware of why it worked on my windows 7 machine and not for windows 8.1 and windows 10, and that is SeDebugPriviledge. I did some research on it, and found a function to enable privledges for it, it return that it has been a success.
void sample()
{
HANDLE hToken = NULL;
TOKEN_PRIVILEGES tokenPriv;
LUID luidDebug;
if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken) != FALSE)
{
if (LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luidDebug) != FALSE)
{
tokenPriv.PrivilegeCount = 1;
tokenPriv.Privileges[0].Luid = luidDebug;
tokenPriv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (AdjustTokenPrivileges(hToken, FALSE, &tokenPriv, 0, NULL, NULL) != FALSE)
{
// Always successful, even in the cases which lead to OpenProcess failure
cout << "SUCCESSFULLY CHANGED TOKEN PRIVILEGES" << endl;
}
else
{
cout << "FAILED TO CHANGE TOKEN PRIVILEGES, CODE: " << GetLastError() << endl;
}
}
}
CloseHandle(hToken);
}
But what happened next is that instead of printing out 0 in the console, it started printing out this negative number, -858993445. Then I decided to try it on a diffrent process, and a different computer, this time on windows 10 instead of windows 8.1, and the same exact number was printed, on three different processes and two different computers running two different OS's. I tried coding the program on windows 7 instead and putting it on a usb and running it on windows 8.1, it was then fully working. But when I coded it and debugged it, it didn't work. Does anyone have any experience with this issue and how I can bypass this, I know it is there for security reasons, but I need PROCESS_ALL_ACCESS for practising reverse engineering.
DISCLAIMER: THIS IS NOT FOR HACKING OR MALWARE DEVELOPMENT PURPOSES, IF I WANTED TO CHEAT IN A VIDEO GAME I COULD JUST DOWNLOAD A CHEAT ONLINE
EDIT: I should add that my computer can't find secpol.msc
The ReadProcessMemory function:
int main()
{
int points;
sample();
DWORD pID;
HWND hWnd = FindWindowA(0, ("Call of Duty®: Black Ops"));
GetWindowThreadProcessId(hWnd, &pID);
HANDLE pHandle = OpenProcess(PROCESS_VM_READ, FALSE, pID);
ReadProcessMemory(pHandle, (LPVOID)0x1C0A6C8, &points, sizeof(points), 0);
cout << points << endl;
system("pause");
}

I did no changes to my code or computer, but out of no where it started working again, strange.

Related

Programmatically Setting Breakpoints on Multi-threaded 64-bit Applications

I have adapted some code from other sources (primarily here) and had no avail in my circumstance. I am attaching to a 64-bit application that has upwards of 100 threads at any given time. There are two issues I have, somewhat unrelated:
Whenever the code hits DebugActiveProcess(pid), the attached application freezes.
The code I have only sets a breakpoint on the main thread, but I need it on more than one - ideally all.
I have confirmed that when the code hits SetThreadContext(hThread, &ctx) the dr0 and dr7 registers change as intended, so that much is fine. The only issues I can see right now are the process freezing and setting more than one breakpoint (I thought of iterating for every single thread which would be fine one-time, but when it gets into the while loop that would obviously be problematic and very resource-consuming). I should also note that I can attach the CheatEngine debugger to the application, and breakpoints work fine with no issues. Below is the code I'm using:
DWORD GetProcessThreadID(DWORD dwProcessID)
{
THREADENTRY32 te = { sizeof(THREADENTRY32) };
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (Thread32First(hSnapshot, &te))
while (Thread32Next(hSnapshot, &te))
if (te.th32OwnerProcessID == dwProcessID)
return te.th32ThreadID;
return NULL;
}
BOOL SetDebugPrivilege(BOOL State)
{
HANDLE hToken;
TOKEN_PRIVILEGES token_privileges;
DWORD dwSize;
ZeroMemory(&token_privileges, sizeof(token_privileges));
token_privileges.PrivilegeCount = 1;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &hToken))
return FALSE;
if (!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &token_privileges.Privileges[0].Luid))
{
CloseHandle(hToken);
return FALSE;
}
if (State)
token_privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
else
token_privileges.Privileges[0].Attributes = SE_PRIVILEGE_REMOVED;
if (!AdjustTokenPrivileges(hToken, FALSE, &token_privileges, 0, NULL, &dwSize))
{
CloseHandle(hToken);
return FALSE;
}
return CloseHandle(hToken);
}
void CreateBreakpoint(DWORD pid, DWORD64 addr) {
DebugActiveProcess(pid);
DebugSetProcessKillOnExit(false);
DWORD_PTR dwThreadID = GetProcessThreadID(pid);
std::cout << std::hex << dwThreadID << std::endl;
HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, dwThreadID);
SetDebugPrivilege(true);
CONTEXT ctx = { 0 };
ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS | CONTEXT_INTEGER;
ctx.Dr0 = addr;
ctx.Dr7 = 0x00000001;
SetThreadContext(hThread, &ctx);
DEBUG_EVENT dbgEvent;
while (true) {
if (WaitForDebugEvent(&dbgEvent, INFINITE) == 0)
break;
if (dbgEvent.dwDebugEventCode == EXCEPTION_DEBUG_EVENT &&
dbgEvent.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_SINGLE_STEP) // EXCEPTION_BREAKPOINT
{
if (dbgEvent.u.Exception.ExceptionRecord.ExceptionAddress == (LPVOID)addr)
{
GetThreadContext(hThread, &ctx);
std::cout << ctx.Rax << "\n";
ctx.Dr7 = 0;
SetThreadContext(hThread, &ctx);
}
}
ContinueDebugEvent(dbgEvent.dwProcessId, dbgEvent.dwThreadId, DBG_CONTINUE);
}
}
It may be worth noting that this is a C++ extension to a python script, but that shouldn't really be relevant, and even if I run the code standalone it runs into the same issues. Also, I'm not an expert in C++ so I apologize if there are any misunderstandings.
I agree with Taekahn, unless you give more information on what you are trying to do, why not use a normal debugger? if you just want to read the registers, any debugger can do that. You can even set breakpoints in disassembly or random addresses, or set data breakpoints.
IDK about gdb, but even in visual studio you can set conditions and actions on breakpoints. It's not as powerfull as c++ code but again, without more informations...
If you want to modify the behavior of the application, that's not how we do it, and using a debugger can actually cause issues.

c++ my program cannot initialize a handle on a process

I'm trying to edit memory in a program. For the most part the code works, but when I try to initiate a handle on the process, it returns NULL.
#include <iostream>
#include <windows.h>
using namespace std;
int main() {
int playerTotalRam = 761;
HWND hwnd = FindWindowA(NULL, "generic game"); // specifies the window to act
upon
// error message if the window isn't found
if (hwnd == NULL) {
cout << "window not found!\n";
system("PAUSE");
} else {
DWORD processID;
// stores the process id of the window
GetWindowThreadProcessId(hwnd, &processID);
// gets the process id of the window
HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processID);
// opens the process with full access
if (!handle) {
cout << "couldnt initiate a handle on the process!\n";
system("PAUSE");
}
// error message if the process ID isn't found
if (processID == NULL) {
cout << "cannot find process!\n";
system("PAUSE");
} else {
WriteProcessMemory(handle, (LPVOID)0x044A52C8, &playerTotalRam,
4, 0); // this writes the new value to the listed address
}
}
return 0;
}
The program outputs "couldnt initiate a handle on the process!"
I have this same error with other programs.
What i want to know is what am I doing wrong, and how can I fix this.
My system is windows 10 home.
Either FindWindowA is failing, resulting in an incorrect process id because you have the wrong window title text or you're not running your program as administrator. You need to run as administrator to get PROCESS_ALL_ACCESS permissions and make sure your title text is correct. This will solve your problem.

Running Process in system context

Is it possible to launch process in system context from a parent process thats running under administrator account with elevation(say a command prompt). The problem is similar to what psexec does but more of how it actually implements this.
I was thinking opening the crss.exe/winlogon.exe process duplicating the token and launching a new process using that process token. But I fail to even open the process handle (Getlasterror return 5). Can someone let me know if this is the right approach or the process should be launched differently ?
HANDLE hWinLogonProcess;
for(const auto& ps : running_processes)
{
if(ps.id == GetCurrentProcessId() ||
0 != ps.short_name.CompareNoCase(L"winlogon.exe"))
{
continue;
}
DWORD dwWinLogonSessionId(0);
if(FALSE == ProcessIdToSessionId(GetCurrentProcessId(), &dwWinLogonSessionId))
{
std::wcerr<<"Could not get Winlogon process session id"<<std::endl;
continue;
}
if(dwWinLogonSessionId != dwCurSessionId)
{
continue;
}
hWinLogonProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, ps.id);
if(FALSE == hWinLogonProcess)
{
std::wcerr<<"Failed to get winlogon process handle"<<std::endl;
return;
}
else
{
std::wcout<<"Able to open process "<<ps.short_name.GetString()<<" handle"<<std::endl;
break;
}
}
I am sure its possible as there is a working tool (psexec) but I couldnt find any reference online to do this.
Also this is similar to question, but posting separately as there was details on how it had to be achieved.
Yes, this is possible (without any service help).
But I fail to even open the process handle
Does your process have the SE_DEBUG_PRIVILEGE privilege enabled?
With this privilege, you can open a system process with all access if it is not protected (smss.exe, csrss.exe, services.exe), and use that handle in CreateProcessAsUser(), or with UpdateProcThreadAttribute(PROC_THREAD_ATTRIBUTE_PARENT_PROCESS) if you also have SE_ASSIGNPRIMARYTOKEN_PRIVILEGE and SE_TCB_PRIVILEGE privileges enabled (for setting the token's SessionId to 0), which you can get in 2 ways:
open a thread from an unprotected system process and impersonate it, then open your own thread token and adjust privileges on it.
open a token from any system process (this works even for protected processes), duplicate the token, adjust privileges on it, and then impersonate with this token.
To "launch a process in the system context", if you want to run the process:
with the LocalSystem token.
in the System terminal session (0)
Both, as I say, are possible. And all you need is SE_DEBUG_PRIVILEGE.
more simply - open some system process with PROCESS_CREATE_PROCESS access right. Use this handle with UpdateProcThreadAttribute(PROC_THREAD_ATTRIBUTE_PARENT_PROCESS). As a result, your started process inherits a token from the system process. This will be not work on XP, but there it is possible to hook NtCreateProcess/Ex() to replace HANDLE ParentProcess with your opened handle.
Another way is to use CreateProcessAsUser(). Before creating the process, you will be need SE_ASSIGNPRIMARYTOKEN_PRIVILEGE and SE_TCB_PRIVILEGE privileges to set the token's TokenSessionId (if you want to run in session 0).
Thanks to RbMm answer I figured a way to accomplish this task.
For any of you who did not succeed, I leave below something that might help:
//First we need to add debug privilege to this process
HANDLE hToken;
if(!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
&hToken))
{
std::cout << "OpenProcessToken failed: " << GetLastError();
return 0;
}
TOKEN_PRIVILEGES tk;
tk.PrivilegeCount = 1;
tk.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if(!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &tk.Privileges[0].Luid))
{
std::cout << "LookupPrivilegeValue failed: " << GetLastError();
return 0;
}
AdjustTokenPrivileges(hToken, FALSE, &tk, 0, NULL, 0);
if((DWORD res = GetLastError()) != ERROR_SUCCESS)
{
std::cout << "AdjustTokenPrivileges failed: " << res;
}
CloseHandle(hToken);
//Now we need a handle to a process that already runs as SYSTEM.
//You can choose any process that is not protected (if OpenProcess fails try with other process)
//pid of chosen process (you can get this by opening task manager and go to
//Details tab or by enumerating all processes and extract that one you need)
DWORD pid;
HANDLE hProcess = OpenProcess(PROCESS_CREATE_PROCESS, FALSE, pid);
if (!hProcess)
{
std::cout << "OpenProcess with pid " << pid << "failed: " << GetLastError();
return 0
}
//We need to initialize a list that contains PROC_THREAD_ATTRIBUTE_PARENT_PROCESS
//to specify that parent process of the process we are going to start is the
//process we opened earlier (this will make the child process inherit the system context).
//This list will be specified in a STARTUPINFOEX object that CreateProcess will get
STARTUPINFOEX siex = { sizeof(STARTUPINFOEX) };
siex.StartupInfo.cb = sizeof(STARTUPINFOEXW);
//We need to initialize our list. To do this we call InitializeProcThreadAttributeList
//with a NULL list to get how big our list needs to be to store all attributes
//we want to specify, then we allocate our list with the size we got from first call
//and we call again the function to initialize the list.
SIZE_T cbAttributeListSize = 0;
if(!InitializeProcThreadAttributeList(NULL, 1, 0, &cbAttributeListSize))
{
std::cout << "InitializeProcThreadAttributeList failed: " << GetLastError();
return 0
}
siex.lpAttributeList = reinterpret_cast<PPROC_THREAD_ATTRIBUTE_LIST>(HeapAlloc(GetProcessHeap(), 0, cbAttributeListSize));
if(!InitializeProcThreadAttributeList(siex.lpAttributeList, 1, 0, &cbAttributeListSize))
{
std::cout << "InitializeProcThreadAttributeList failed: " << GetLastError();
return 0
}
if(!UpdateProcThreadAttribute(siex.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, &hProcess, sizeof(hProcess), NULL, NULL))
{
std::cout << "UpdateProcThreadAttribute failed: " << GetLastError();
return 0
}
//path to program we want to run in system context
LPWSTR szCmdline = _wcsdup(TEXT("C:\\Windows\\System32\\notepad.exe"));
PROCESS_INFORMATION pi = { 0 };
if(!CreateProcess(NULL, szCmdline, nullptr, nullptr, FALSE, EXTENDED_STARTUPINFO_PRESENT, NULL, NULL, reinterpret_cast<LPSTARTUPINFOW>(&siex), &pi))
{
std::cout << "CreateProcess failed: " << GetLastError();
return 0
}

Write/Read a memory-protected process's memory

I'll try to explain my problem the best I can.
I'm trying to access to a memory-protected process memory (Minesweeper).
I'll put my code first and then I'll explain what's the thing I want to archieve. (If you read everything and know another way to do this, please post it).
First, the getProcessHandle, a function that returns a open handle to the process with name procName.
It works perfectly, and I can list all the processes.
HANDLE getProcessHandle(const wchar_t *procName){
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 procEnt;
procEnt.dwSize = sizeof(PROCESSENTRY32);
Process32First(snap, &procEnt);
printf("--Listando procesos...\n");
do{
printf("Process name: %S \n", procEnt.szExeFile);
if (!wcscmp(procName, procEnt.szExeFile)){
printf("Encontrado %S.\n\n", procName);
return OpenProcess(PROCESS_ALL_ACCESS, FALSE, procEnt.th32ProcessID);
}
} while (Process32Next(snap, &procEnt));
printf("No se ha encontrado el proceso.");
CloseHandle(snap);
return NULL;
Second, the getModule function. Its work should be finding and enumerating all the modules in the process passed as a HANDLE.
HMODULE getHModule(HANDLE procHandle, const wchar_t *procName){
HMODULE moduleHandle[1024];
DWORD bytesNeeded;
unsigned int i = 0;
if (EnumProcessModulesEx(procHandle, moduleHandle, sizeof(moduleHandle), &bytesNeeded, LIST_MODULES_ALL)){
printf("--Modulos del proceso:\n");
for (i = 0; i < (bytesNeeded / sizeof(HMODULE)); i++){
TCHAR pathModule[1024];
GetModuleBaseName(procHandle, moduleHandle[i], pathModule, sizeof(pathModule) / sizeof(TCHAR));
if (!wcscmp(procName, pathModule)){
printf("Encontrado modulo %S.", procName);
return moduleHandle[i];
}
printf("Module %d: %S \n", i + 1, pathModule);
}
printf("No se ha encontrado el modulo.");
return NULL;
}
else {
printf("Error en EnumProcessModulesEx n: %ls", GetLastError());
}
return NULL;
And the problem comes here. When I try to enumerate all the modules in the process, if the process is a normal process, I mean, a not-memory-protected process, it works perfectly.
The problem is when the process is memory-protected.
At this point, I decided to search, and I discovered the Privilege Tokens. It's said that if I get the SE_DEBUG_NAME token activated, my process could surpass the protection, so, I've done that function:
int privileges(){
HANDLE token;
TOKEN_PRIVILEGES tp;
DWORD siz = sizeof(TOKEN_PRIVILEGES);
if (OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &token) != 0){
LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &tp.Privileges[0].Luid);
tp.PrivilegeCount = 1;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (AdjustTokenPrivileges(token, 0, &tp, siz, NULL ,NULL) != 0){
cout << "--Conseguido acceso debug.\n";
return TRUE;
}
else {
cout << "fail adjust\n";
return FALSE;
}
}
else {
cout << "fail if: " << GetLastError() << endl;
cin.get();
return FALSE;
}
And the "main" function:
int _tmain(int argc, _TCHAR* argv[])
{
privileges();
wchar_t *processName = _T("calc.exe");
HANDLE hProc = getProcessHandle(processName);
if (hProc){
HMODULE hMod = getHModule(hProc, processName);
cout << hMod;
}
cin.get();
return 0;
}
The problem I have right now is, when I execute this function, privileges(), it returns the ERROR_NO_TOKEN code number.
Someone here said me to change the OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &token) for an OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token), and that causes no problem, neither result, with that fix, I have the same problem as if privileges() is not executed.
Thanks for reading all the text, and, if is there another way to do this, please tell me, I'm trying to learn.
The documentation for EnumProcessModulesEx says:
This function is intended primarily for 64-bit applications. If the function is called by a 32-bit application running under WOW64, the dwFilterFlag option is ignored and the function provides the same results as the EnumProcessModules function.
Going to the documentation for EnumProcessModules, we find:
If this function is called from a 32-bit application running on WOW64, it can only enumerate the modules of a 32-bit process.
So to work on a 64-bit process, your code will have to be 64-bit itself.
The documentation continues:
If the process is a 64-bit process, this function fails and the last error code is ERROR_PARTIAL_COPY (299).
It seems that this may be incorrect, since you were receiving a access violation exception instead.
Write ImpersonateSelf(SecurityImpersonation); like here:
ImpersonateSelf(SecurityImpersonation);
OpenThreadToken
(
GetCurrentThread(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
FALSE,
&token
);
The ImpersonateSelf makes function obtains an access token that impersonates the security context of the calling process. The token is assigned to the calling thread.
To see all the SECURITY_IMPERSONATION_LEVELs click here

Prevent process from being closed in task manager

I am developing a little program for becoming more productive. It should disconnect the user from the Internet or shut your computer down after a preset number of minutes. The program shouldn't be closed with task manager. I could compile the program and it run, but I could close it with task manager. I got my inspiration from this page:
#include <iostream>
#include <Windows.h>
#include <AccCtrl.h>
#include <AclAPI.h>
#include <tchar.h>
#include "shutdown.cpp"
#include "disconnect.cpp"
static const bool ProtectProcess()
{
HANDLE hProcess = GetCurrentProcess();
EXPLICIT_ACCESS denyAccess = {0};
DWORD dwAccessPermissions = GENERIC_WRITE|PROCESS_ALL_ACCESS|WRITE_DAC|DELETE|WRITE_OWNER|READ_CONTROL;
BuildExplicitAccessWithName( &denyAccess, _T("CURRENT_USER"), dwAccessPermissions, DENY_ACCESS, NO_INHERITANCE );
PACL pTempDacl = NULL;
DWORD dwErr = 0;
dwErr = SetEntriesInAcl( 1, &denyAccess, NULL, &pTempDacl );
// check dwErr...
dwErr = SetSecurityInfo( hProcess, SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, pTempDacl, NULL );
// check dwErr...
LocalFree( pTempDacl );
CloseHandle( hProcess );
return dwErr == ERROR_SUCCESS;
}
int main()
{
using namespace std;
int abfrage;
ProtectProcess();
for (;;)
{
cout << "10.Cut your Internet connection" << endl
<< "11.Cut your Internet connection after 'x' minutes of surfing" << endl
<< "20.Shutdown" << endl;
cin >> abfrage;
switch(abfrage)
{
case 10: disconnectnow(); break;
case 11: disconnectlater(); break;
case 20: shutdown(); break;
default: cout << "nothing to see here" << endl;
}
}
return EXIT_SUCCESS;
}
This functionality is, deliberately, unsupported and actively made intractable:
Why can't you trap TerminateProcess?
If a user fires up Task Manager and clicks the End Task button on the Applications tab, Windows first tries to shut down your program nicely, by sending WM_CLOSE messages to GUI programs and CTRL_CLOSE_EVENT events to console programs. But you don't get a chance to intercept TerminateProcess. Why not?
TerminateProcess is the low-level process-killing function. It bypasses DLL_PROCESS_DETACH and anything else in the process. When you kill with TerminateProcess, no more user-mode code will run in that process. It's gone. Do not pass go. Do not collect $200.
If you could intercept TerminateProcess, you would be escalating the arms race between programs and users. Suppose you could intercept it. Well, then if you wanted to make your program unkillable, you would just hand in your TerminateProcess handler! And then people would ask for "a way to kill a process that is refusing to be killed with TerminateProcess," and we'd be back to where we started.
In practice, programs attempting to evade detection and task kill try to rename themselves to near isoforms of the Windows system processes. Don't do this. It guarantees your program will be submitted as malware and will kill your credibility dead.