OpenThreadToken() error 1008, ERROR_NO_TOKEN - c++

I'm trying to read from the memory of the MineSweeper to learn that kind of stuff, but I have a little problem.
When I try to print the modules it says to me I have no rights to do that. I know that's because the memory of that process is protected from write-read, and to read from it, I need to have debug rights.
And right there, my problem is when I call the OpenThreadToken(..), it fails with code 1008, and that's ERROR_NO_TOKEN.
Here you are the code, and sorry for the long intro:
int privileges(){
HANDLE token;
TOKEN_PRIVILEGES tp;
DWORD siz = sizeof(TOKEN_PRIVILEGES);
if (OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
FALSE, &token) != 0){ //HERE IT FAILS
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;
}
I don't know why it fails. I've tried with the Microsoft example too, but same problem.
Does anybody know why it fails?

Threads only have their own tokens if you are using the impersonation APIs, otherwise there is only a process token. Simply fall back to OpenProcessToken if OpenThreadToken fails with ERROR_NO_TOKEN.

Related

ERROR_ACCESS_DENIED when using CreateToolhelp32Snapshot() against specific process

Trying to play with different processes to read data from the memory. And for some reason it works for almost all processes on my pc but fails with only one specific (so far). I can't understand why its happening and if there some kind of security stuff applied or what? Any help will be appreciated.
The process that I'm trying hook is x64 but I've tested this code with different x64 processes and it worked without issue. So I don't think its compile/x32/x64 problem. I will be happy if some one can tell when to go from there.
So I can get the correct Process Id but fail to read modules from:
uintptr_t GetModuleBaseAddress(DWORD procId, const wchar_t* modName) {
uintptr_t modBaseAdr = 0;
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, procId);
if (hSnap == INVALID_HANDLE_VALUE) {
DWORD errorCode = GetLastError();
if (ERROR_ACCESS_DENIED == errorCode) {
std::cout << "Got Error Access Denied code: " << errorCode << std::endl;
}
else {
std::cout << "Unhandled error code: " << errorCode << std::endl;
}
}
else {
MODULEENTRY32 modEntry;
modEntry.dwSize = sizeof(modEntry);
if (Module32First(hSnap, &modEntry)) {
do {
if (!_wcsicmp(modEntry.szModule, modName)) {
modBaseAdr = (uintptr_t)modEntry.modBaseSize;
break;
}
} while (Module32Next(hSnap, &modEntry));
}
}
CloseHandle(hSnap);
return modBaseAdr;
}
Output:
procId = 0x4398
Got Error Access Denied code: 5
UPD:
0x4398 process (actually a game) which is running from my user. its not the system or protected process.

WINAPI Read all access rights for a custom file or a folder

I have a task based on an algorithm to receive the access rights for a certain file or folder and I've tried to implement it but some parts don't seem to be clear.
What I've been asked for:
1) Use the function GetNamedSecurityInfo(), for example:
GetNamedSecurityInfo(path,SE_FILE_OBJECT,DACL_SECURITY_INFORMATION,NULL,
NULL,&a,NULL, &pSD)
2) Futher, use an SID to receive the rights: Use
these functions to receive the SID: GetAclInformation(), then GetAce().
3) Now you can use the LookupAccountSid() function and if is was
successfull, compare pACE->Mask with all the constants, for example
"GENERIC_ALL, GENERIC_READ, GENERIC_WRITE, GENERIC_EXECUTE for files
etc." displaying the access rights.
And how I tried to implement this algorithm: // First getting process SID
PSID g_pSID;
BOOL GetCurrentProcessSID()
{
DWORD dwSize = 0, dwError, dwResult = 0;
HANDLE hToken;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
{
printf("OpenProcessToken Error %u\n", GetLastError());
return FALSE;
}
// Call GetTokenInformation to get the buffer size.
TOKEN_USER tU;
if (!GetTokenInformation(hToken, TokenUser, &tU, 0, &dwSize))
{
dwError = GetLastError();
if (dwError != ERROR_INSUFFICIENT_BUFFER)
{
std::cout << "GetTokenInformation failed, error " << dwError;
CloseHandle(hToken);
return 0;
}
}
PTOKEN_OWNER to = (PTOKEN_OWNER)LocalAlloc(LPTR, dwSize);
if (!to)
{
dwError = GetLastError();
std::cout << "LocalAlloc failed, error " << dwError;
CloseHandle(hToken);
return 0;
}
if (!GetTokenInformation(hToken, TokenOwner, to, dwSize, &dwSize))
{
dwError = GetLastError();
std::cout << "GetTokenInformation failed, error " << dwError;
LocalFree(to);
CloseHandle(hToken);
return 0;
}
g_pSID = to->Owner;
return TRUE;
}
//Then I used the iteration through the ACL list:
std::stringstream g_TestSecurityResult;
void TestSecurity( wchar_t* path )
{
g_TestSecurityResult = std::stringstream();
GetCurrentProcessSID();
PACL pDacl;
PSECURITY_DESCRIPTOR pSD;
GetNamedSecurityInfoW(path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &pDacl, NULL, &pSD);
ACL_SIZE_INFORMATION aclSizeInfo = { sizeof(ACL) };
BOOL fResult = GetAclInformation( pDacl, &aclSizeInfo, sizeof(ACL_SIZE_INFORMATION), ACL_INFORMATION_CLASS::AclSizeInformation );
if (fResult)
{
for (DWORD dwIndex = 0; dwIndex < aclSizeInfo.AceCount; ++dwIndex)
{
LPVOID pTempAce = nullptr;
fResult = ::GetAce(pDacl, dwIndex, &pTempAce);
if (fResult)
{
PSID pSid = &((ACCESS_ALLOWED_ACE*)pTempAce)->SidStart;
if (EqualSid(pSid, &g_pSID))
{
g_TestSecurityResult << "User: " << userNameFromSid(&g_pSID) << std::endl;
g_TestSecurityResult << "\tAccess mode: " << ((EXPLICIT_ACCESS*)pTempAce)->grfAccessMode << "\n";
g_TestSecurityResult << "\tAccess permissions: " << ((EXPLICIT_ACCESS*)pTempAce)->grfAccessPermissions << "\n";
g_TestSecurityResult << "\tInheritance: " << ((EXPLICIT_ACCESS*)pTempAce)->grfInheritance << "\n";
g_TestSecurityResult << std::endl;
}
}
else
{
g_TestSecurityResult << "GetAce() failed." << GetLastError();
break;
}
}
} else {
g_TestSecurityResult << "Error in GetAclInformation(): " << GetLastError();
}
}
std::string userNameFromSid(PSID userSid)
{
char buffName[MAX_BUFF_SIZE];
DWORD buffNameSize = MAX_BUFF_SIZE;
char buffDomain[MAX_BUFF_SIZE];
DWORD buffDomainSize = MAX_BUFF_SIZE;
SID_NAME_USE SidType;
if (LookupAccountSid(NULL, userSid, buffName, &buffNameSize, buffDomain, &buffDomainSize, &SidType)) {
return buffName;
} else {
DWORD dwResult = GetLastError();
printf("GetTokenInformation Error %u\n", dwResult);
}
/*Here some code to print error in a Message box*/
return "";
}
The problem: The code is working but at the line if (EqualSid(pSid, &g_pSID)) debugger goes through and skips the SID that I've received from my process. In other words, I can't get any information from the ACL list, even though I'm running the process and Visual Studio under Administrator account (not using the "Run as Administrator", and I'll try it but still... The received SID is valid and I can get the name of the process owner using the above function. What could be something that I'm doing wrong here?
Code sources:
https://gist.github.com/m4x1m1l14n/37f39c5d25855c2b1d3a6334851f7549
How to get the logged-on user's SID in Windows
GetTokenInformation, TOKEN_OWNER, и LookupAccountSidA
Thanks to #(Rita Han - MSFT) comment, I've forgotten to remove the ampersand mark from the pSID comparison
EqualSid(pSid, g_pSID);
instead of
EqualSid(pSid, &g_pSID);
And It's properly working for now

C++ ReadProcessMemory receiving 998 / 3E6 Error

So I'm trying to read Memory out of a running exe with ReadProcessMemory() as you can see in the code provided below.
The only problem I constantly run into is that I receive the Error 3E6 / 998 which seems to be NOACCESS but I cant find a solution to fix this.
And yes I tried to run the exe in Admin Mode without success...
#include <Windows.h>
#include <iostream>
#include <string>
#include <tlhelp32.h>
#include <Psapi.h>
#include <tchar.h>
using namespace std;
int id = NULL;
HANDLE hProcess = NULL;
int getPID(const string name);
bool setHandle(int id, HANDLE &out);
DWORD64 GetModule(const string name);
int main()
{
bool success = false;
id = getPID("sample.exe");
string name = "SAMPLE";
cout << "Process Name: " << name << endl;
cout << "Process ID: " << id << endl;
success = setHandle(id, hProcess);
if (success)
{
cout << "Handle set..." << endl;
}
else if (!success)
{
cout << "You need to have SOMETHING opened..." << endl;
cout << "ERROR CODE: " << GetLastError() << endl;
system("pause");
return 1;
}
success = false;
DWORD64 baseAddress = GetModule("sample.exe");
DWORD64 ammo = 0x24ED13273A8;
DWORD64 addr = baseAddress + ammo;
cout << "Base Address: " << hex << uppercase << "0x" << baseAddress << endl;
cout << "Ammo Address: " << hex << uppercase << "0x" << ammo << endl;
cout << "Complete Address: " << hex << uppercase << "0x" << addr << endl;
int buffer = 0;
success = ReadProcessMemory(hProcess, (LPCVOID)addr, (LPVOID)&buffer, sizeof(&buffer), NULL);
if (success)
{
cout << "ReadProccess succeeded..." << endl;
system("pause");
return 0;
}
else if (!success)
{
cout << "ERROR CODE: " << GetLastError() << endl;
system("pause");
return 1;
}
system("pause");
return 0;
}
bool setHandle(int id, HANDLE &out)
{
out = OpenProcess(PROCESS_ALL_ACCESS, FALSE, id);
if (!out) return false;
return true;
}
int getPID(const string name)
{
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (!Process32First(snapshot, &entry)) return NULL;
do
{
if (strcmp(entry.szExeFile, name.c_str()) == 0)
{
CloseHandle(snapshot);
return entry.th32ProcessID;
}
} while (Process32Next(snapshot, &entry));
CloseHandle(snapshot);
return NULL;
}
DWORD64 GetModule(const string name)
{
HMODULE hMods[1024];
DWORD cbNeeded;
if (EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded))
{
for (int i = 0; i < (cbNeeded / sizeof(HMODULE)); i++)
{
TCHAR szModName[MAX_PATH];
if (GetModuleFileNameEx(hProcess, hMods[i], szModName, sizeof(szModName) / sizeof(TCHAR)))
{
string modName = szModName;
if (modName.find(name) != string::npos)
{
return (DWORD64)hMods[i];
}
}
}
}
return NULL;
}
I'm kinda new to c++... so sry? :)
There are actually two basic mistakes in your code, both of which, unfortunately for you, me and the rest of the civilised world, generate the same error code. Was it ever thus. There is also a logic error, but you are lucky enough to be getting away with it (just about). I commented the fix in the code I posted below.
There are also a number of 'good practise' shortcomings in your code, specifically:
NULL should not be used to represent integer zero
All error conditions should be checked for and (sensibly!) reported
You use the same string literal in two different places (so if you ever change it, you would need to change it in both places, and you might forget). So don't do that.
using namespace std; is widely frowned upon (because it causes such a lot of namespace pollution)
Why are id and hProcess global variables? This is just plain unnecessary.
You should give your functions more descriptive names, setHandle being the one I particularly have in mind. I got rid of that one completely.
When passing a std::string as a read-only function parameter, it is usually best to pass it as const ref, then it doesn't need to be copied.
Only use std::endl when you actually want to flush the buffer. It is inefficient.
Clean up after you (in this case, close any open handles). I know this is just a throwaway program but it's a good habit to get into.
OK, so here's some code that works (I have posted my own because I cleaned up all of the above). The substantive changes are:
To read the memory of another process, you need to give your user token the SE_DEBUG_NAME privilege. This in turn means you need to run your program as Administrator (aka elevated).
You cannot (obviously) read from a nonsense address in the target process so I just quietly fixed that.
Like I say, both of these generate the same error code. Huh!
OK, here you go. Enjoy:
#include <Windows.h>
#include <iostream>
#include <string>
#include <tlhelp32.h>
#include <Psapi.h>
#include <tchar.h>
int getPID(const std::string& name);
DWORD64 GetModule(HANDLE hProcess, const std::string& name);
// Stolen from: https://learn.microsoft.com/en-gb/windows/desktop/SecAuthZ/enabling-and-disabling-privileges-in-c--
BOOL SetPrivilege(
HANDLE hToken, // access token handle
LPCTSTR lpszPrivilege, // name of privilege to enable/disable
BOOL bEnablePrivilege // to enable or disable privilege
)
{
TOKEN_PRIVILEGES tp;
LUID luid;
if ( !LookupPrivilegeValue(
NULL, // lookup privilege on local system
lpszPrivilege, // privilege to lookup
&luid ) ) // receives LUID of privilege
{
printf("LookupPrivilegeValue error: %u\n", GetLastError() );
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;
// Enable the privilege or disable all privileges.
if ( !AdjustTokenPrivileges(
hToken,
FALSE,
&tp,
sizeof(TOKEN_PRIVILEGES),
(PTOKEN_PRIVILEGES) NULL,
(PDWORD) NULL) )
{
printf("AdjustTokenPrivileges error: %u\n", GetLastError() );
return FALSE;
}
if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
{
printf("The token does not have the specified privilege. \n");
return FALSE;
}
return TRUE;
}
constexpr const char* theProcess = "notepad.exe";
int main()
{
HANDLE hToken;
BOOL ok = OpenProcessToken (GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken);
if (!ok)
{
std::cout << "OpenProcessToken failed, error " << GetLastError() << "\n";
return 255;
}
ok = SetPrivilege (hToken, SE_DEBUG_NAME, TRUE);
if (!ok)
{
CloseHandle (hToken);
return 1;
}
int pid = getPID (theProcess);
HANDLE hProcess = OpenProcess (PROCESS_ALL_ACCESS, FALSE, pid);
if (hProcess == NULL)
{
std::cout << "OpenProcess failed, error " << GetLastError() << "\n";
CloseHandle (hToken);
return 1;
}
DWORD64 baseAddress = GetModule(hProcess, theProcess);
std::cout << "Base Address: " << std::hex << std::uppercase << "0x" << baseAddress << "\n";
int buffer = 0; // Note: sizeof (buffer) below, not sizeof (&buffer)
ok = ReadProcessMemory(hProcess, (LPCVOID)baseAddress, (LPVOID)&buffer, sizeof(buffer), NULL);
CloseHandle (hProcess);
CloseHandle (hToken);
if (ok)
{
std::cout << "ReadProcessMemory succeeded, buffer = " << buffer << "\n";
system("pause");
return 0;
}
std::cout << "ReadProcessMemory failed, error " << GetLastError() << "\n";
system("pause");
return 1;
}
int getPID(const std::string& name)
{
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (!Process32First(snapshot, &entry)) return NULL;
do
{
if (strcmp(entry.szExeFile, name.c_str()) == 0)
{
CloseHandle(snapshot);
return entry.th32ProcessID;
}
} while (Process32Next(snapshot, &entry));
CloseHandle(snapshot);
return NULL;
}
DWORD64 GetModule(HANDLE hProcess, const std::string& name)
{
HMODULE hMods[1024];
DWORD cbNeeded;
if (EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded))
{
for (int i = 0; i < (cbNeeded / sizeof(HMODULE)); i++)
{
TCHAR szModName[MAX_PATH];
if (GetModuleFileNameEx(hProcess, hMods[i], szModName, sizeof(szModName) / sizeof(TCHAR)))
{
std::string modName = szModName;
if (modName.find(name) != std::string::npos)
{
return (DWORD64)hMods[i];
}
}
}
}
return NULL;
}
Output (when run as Administrator):
Base Address: 0x7FF6D8470000
ReadProcessMemory succeeded, buffer = 905A4D
Output (when run as a normal user):
The token does not have the specified privilege.
You can also grab some code over at GitHub.

Access Violation with FindVolumeClose()

In the following function, when I hit the FindVolumeClose() line, I always get the error outlined below. Any ideas why this happens?
Unhandled exception at 0x11000000 in BootFixFFS.exe: 0xC0000005: Access violation (parameters: 0x00000008).
char buffer[MAX_PATH];
HANDLE hVol = FindFirstVolume(buffer, MAX_PATH);
if (hVol == INVALID_HANDLE_VALUE) {
std::cout << "No volumes found\n.";
return FALSE;
}
std::string strVol = buffer;
strVol.pop_back();
HANDLE hPart = CreateFile(strVol.c_str(), 0, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hPart == INVALID_HANDLE_VALUE) {
FindVolumeClose(hVol);
std::cout << "Couldn't create file: " << GetLastError() << "\n";
return FALSE;
}
int numPartitions = 8;
DWORD dwDliSize = sizeof(DRIVE_LAYOUT_INFORMATION_EX) + numPartitions * sizeof(PARTITION_INFORMATION_EX);
DRIVE_LAYOUT_INFORMATION_EX *dli = (DRIVE_LAYOUT_INFORMATION_EX*) new BYTE[dwDliSize];
DWORD dwSize;
ZeroMemory(&dli, sizeof(dli));
BOOL bSuccess = DeviceIoControl(hPart, IOCTL_DISK_GET_DRIVE_LAYOUT_EX, NULL, 0, &dli, dwDliSize, &dwSize, NULL);
CloseHandle(hPart);
FindVolumeClose(hVol);
if (bSuccess == FALSE) {
std::cout << "Couldn't get device information: " << GetLastError() << "\n";
return FALSE;
}
return TRUE;
It seems to me that ZeroMemory(&dli, sizeof(dli)) is not doing what you want it to do. It erases the address from dli, instead of zeroing the content of the byte array. Maybe ZeroMemory(dli, dwDliSize) is what you meant?
Also, the more serious error is using &dli when calling DeviceIoControl. You are basically overwriting your entire stack, and destroying the local variables.

How to use OpenProcessToken, AdjustTokenPrivileges, and GetExitCodeProcess in VC++ 2005

I read a couple of posts on how to check if a process has exited from a different process (I realize some people get hung up on semantics here, but just humor me) and I tried to implement it but am running into the error code 5 ("ERROR_ACCESS_DENIED") all over the place.
Here is what I do.
1) Process 1 (P1) launches process 2 and writes to a shared memory location its own PID.
2) Process 2 (P2) reads the PID from shared memory
3) P2 calls OpenProcess(...) with P1's PID to save a handle that it can check later.
4) P2 calls GetExitCodeProcess(...) with P1's PID repeatedly and checks for a STILL_ACTIVE code.
In the above method, I keep getting the ACCESS_DENIED error on GetExitCodeProcess. I've tried modifying P2's privileges by using the below code from MSDN's docs:
HANDLE proc_h = OpenProcess(SYNCHRONIZE, FALSE, GetCurrentProcessId());
HANDLE hToken;
OpenProcessToken(proc_h, TOKEN_ADJUST_PRIVILEGES, &hToken);
LookupPrivilegeValue(NULL, lpszPrivilege, &luid );
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
// Enable the privilege
AdjustTokenPrivileges(hToken,
FALSE,
&tp,
sizeof(TOKEN_PRIVILEGES),
(PTOKEN_PRIVILEGES) NULL,
(PDWORD) NULL);
But I keep getting the ACCESS_DENIED error on the call to OpenProcessToken(...) method. So does this indicate some sort of system level hurdle? I do have admin rights on my machine and I'm running XP.
Thanks in advance for any help.
The handle passed to GetExitCodeProcess requires PROCESS_QUERY_INFORMATION access right.
The following works fine:
int main(int a_argc, char** a_argv)
{
int pid = atoi(*(a_argv + 1));
HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
if (NULL != h)
{
Sleep(2000);
DWORD exit_code;
if (FALSE == GetExitCodeProcess(h, &exit_code))
{
std::cerr << "GetExitCodeProcess() failure: " <<
GetLastError() << "\n";
}
else if (STILL_ACTIVE == exit_code)
{
std::cout << "Still running\n";
}
else
{
std::cout << "exit code=" << exit_code << "\n";
}
}
else
{
std::cerr << "OpenProcess() failure: " << GetLastError() << "\n";
}
return 0;
}
Instead of polling on GetExitCodeProcess open the handle with SYNCHRONIZE and wait for it to exit:
int main(int a_argc, char** a_argv)
{
int pid = atoi(*(a_argv + 1));
HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION, FALSE, pid);
if (NULL != h)
{
WaitForSingleObject(h, 5000); // Change to 'INFINITE' wait if req'd
DWORD exit_code;
if (FALSE == GetExitCodeProcess(h, &exit_code))
{
std::cerr << "GetExitCodeProcess() failure: " <<
GetLastError() << "\n";
}
else if (STILL_ACTIVE == exit_code)
{
std::cout << "Still running\n";
}
else
{
std::cout << "exit code=" << exit_code << "\n";
}
}
else
{
std::cerr << "OpenProcess() failure: " << GetLastError() << "\n";
}
return 0;
}
OpenProcesstoken requires PROCESS_QUERY_INFORMATION you are opening the process with only SYNCHRONIZE access. See if you add | PROCESS_QUERY_INFORMATION if it works.
If you just want P2 to do something when P1 exits, there's another way that's probably rather easier: have P1 create a pipe and let P2 inherit a handle to that pipe. In P2, execute a read from the pipe. When P2's call to ReadFile returns with an error of ERROR_BROKEN_PIPE, P1 has exited.