How to stop c++ console from outputting "tick" - c++

I haven't been able to find anything else about this online at all. I have a simple authenticator program, with a .dll injector written into it. If the key matches the one in the database, it will run the injector, and constantly check to make sure that the key is still active. For some reason, my console window outputs "tick" about every second. When the injector is taken out, and it is just the authenticator it will not do this.
#include <iostream>
#include <string>
#include <Windows.h>
#include <thread>
#include <WinInet.h>
#include <TlHelp32.h>
#include <fcntl.h>
#include <io.h>
#include <fcntl.h>
#include <cstdio>
#include <chrono>
#include "include/c0gnito.h"
std::string Key;
std::string hwid = GetHardwareID(); //Gets the hwid
char* StringToChar(std::string string) //A function to convert a string to a char
{
return _strdup(string.c_str());
}
template <class T>
void msg(T msg)
{
std::cout << msg << std::endl;
}
bool FileExists(const std::string& fileName)
{
struct stat buffer;
return (stat(fileName.c_str(), &buffer) == 0);
}
void WriteStringToIni(std::string string, std::string file, std::string app, std::string key)
{
WritePrivateProfileStringA(app.c_str(), key.c_str(), string.c_str(), file.c_str());
}
std::string ReadStringFromIni(std::string file, std::string app, std::string key)
{
char buf[100];
GetPrivateProfileStringA(app.c_str(), key.c_str(), "NULL", buf, 100, file.c_str());
return (std::string)buf;
}
LONG address = 0x0;
BYTE newvalue[] = { 0x0 };
HWND hwnd;
HANDLE phandle;
DWORD pid;
DWORD GetProcId(const char* procName)
{
DWORD procId = 0;
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, procName))
{
procId = procEntry.th32ProcessID;
break;
}
} while (Process32Next(hSnap, &procEntry));
}
}
CloseHandle(hSnap);
return procId;
}
const char* dllPath = "C:\\Windows\\System32\\sysproc.dll";
const char* procName = "Project1.exe";
DWORD procId = 0;
int main() //Entry point
{
system("color b"); //Sets the color to blue
Initialize("B2wVksYPzgCBOtNq8SFQ05GCuKrzwNIRytotMczYWCSv59sypLJhPEnLY9w8cmml"); //Connects to the authentication server
if (FileExists("./Config.ini"))
{
Key = ReadStringFromIni("./Config.ini", "License", "Key"); //Gets the key saved in the file
}
else
{
std::cout << "Welcome, please enter your license key: ";
std::cin >> Key; //Gets the user's key
if (Authenticate(StringToChar(Key), (StringToChar(hwid)))) {}// Authenticates key & hwid
else
{
std::cout << "Invalid Key!" << std::endl;
exit(2000);
}
WriteStringToIni(Key, "./Config.ini", "License", "Key"); //Creates a file that stores the key entered
}
if (Authenticate(StringToChar(Key), (StringToChar(hwid)))) // Authenticates key & hwid
{
std::cout << "Sucessfully Authenticated!" << std::endl;
Sleep(2000);
while (!procId)
{
procId = GetProcId(procName);
Sleep(30);
}
HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, 0, procId);
if (hProc && hProc != INVALID_HANDLE_VALUE)
{
void* loc = VirtualAllocEx(hProc, 0, MAX_PATH, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
WriteProcessMemory(hProc, loc, dllPath, strlen(dllPath) + 1, 0);
HANDLE hThread = CreateRemoteThread(hProc, 0, 0, (LPTHREAD_START_ROUTINE)LoadLibraryA, loc, 0, 0);
if (hThread)
{
CloseHandle(hThread);
}
}
if (hProc)
{
CloseHandle(hProc);
}
}
else
{
exit(0);
}
system("cls");
std::cout << "Hardware ID: " << hwid << std::endl;
std::cout << "_______________________________________________________" << std::endl;
std::cout << " " << std::endl;
std::thread auth([&]() //Authentication Thread that keep on checking the connection and user previleges
{
while (true)
{
std::cout << "Auth is checking..." << std::endl;
if (!Authenticate(StringToChar(Key), (StringToChar(hwid))))
{
exit(0);
}
std::cout << "Sucessfully Authenticated!" << std::endl;
Sleep(60000);
}
});
std::cin.get();
}

Related

my program isnt writing to process memory. how do i debug this? im new to wpm and rpm

`
#include <iostream>
#include <windows.h>
#include <Tlhelp32.h>
HANDLE hProc = NULL;
DWORD pID;
bool attachProc(char* procName)
{
PROCESSENTRY32 procEntry32;
procEntry32.dwSize = sizeof(PROCESSENTRY32);
auto hProcSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if(hProcSnap == INVALID_HANDLE_VALUE)
{
std::cout << "FAILED to take snapshot of processes\n";
return false;
}
while(Process32Next(hProcSnap, &procEntry32))
{
std::cout << procEntry32.szExeFile << std::endl;
if (procEntry32.th32ProcessID != 996)
{
if (!strcmp(procName, procEntry32.szExeFile))
{
std::cout << "found process " << procEntry32.szExeFile << " with process id " << procEntry32.th32ProcessID << std::endl;
hProc = OpenProcess(PROCESS_ALL_ACCESS,FALSE,procEntry32.th32ProcessID);
pID = procEntry32.th32ProcessID;
if (hProc == NULL)
{
std::cout << "failed getting handle to process" << std::endl;
}
CloseHandle(hProcSnap);
return true;
}
}
}
std::cout << "couldnt find " << procName << "in the process snapshot" << std::endl;
CloseHandle(hProcSnap);
return false;
}
template <class dataType>
void wpm(dataType valToWrite, DWORD adressToWrite)
{
WriteProcessMemory(hProc, (PVOID)adressToWrite, &valToWrite, sizeof(dataType), 0);
}
template <class dataType>
dataType rpm(DWORD adressToRead)
{
dataType rpmBuffer;
ReadProcessMemory(hProc, (PVOID)adressToRead, &rpmBuffer, sizeof(dataType), 0);
return rpmBuffer;
}
int main()
{
DWORD memoryAdress = 0x288469A7A28;
int value = 1
attachProc((char*)"dummy.exe");
while (true)
{
wpm<int>(value, memoryAdress);
}
}
`
i think there is a problem in getting the handle but i dont know where or how do i debug this.
is there any different way on how to get a handle? bestsides FindWindow() because this doesnt work either
i was trying to write process memory but id didnt work for some reason the adress should be good i tested it in cheat engine multiple times

WaitForSingleObject with FindFirstChangeNotification not behaving as expected [duplicate]

This question already has answers here:
FindFirstChangeNotification is notifying about changes twice
(2 answers)
Closed 1 year ago.
I have to find out if there is a new file in a directory on Windows. Following this MSDN example (Obtaining Directory Change Notifications), I came up with the following test program:
#include <iostream>
#include <Windows.h>
#include <vector>
#include <string>
std::string FindNewFile(std::vector<std::string>& vsNewFileList, std::vector<std::string>& vsOldFileList)
{
std::string sNewFileName;
int nScore = 0;
for (auto& newFile : vsNewFileList)
{
nScore = 0;
for (auto& oldFile : vsOldFileList)
if(!newFile.compare(oldFile))
nScore++;
if (nScore!=1)
{
sNewFileName = newFile;
break;
}
}
return sNewFileName;
}
void GetCurrentFilesInDir(std::string sDir, std::vector<std::string>& vsFileList)
{
WIN32_FIND_DATA ffd;
sDir += "\\*";
std::wstring wStr = std::wstring(sDir.begin(), sDir.end());
LPCWSTR lpcwsDir = (LPCWSTR)wStr.c_str();
HANDLE hFind = FindFirstFile(lpcwsDir, &ffd);
if (hFind == INVALID_HANDLE_VALUE)
{
std::cout << "Nope\n";
return;
}
vsFileList.clear();
do
{
int nSize = WideCharToMultiByte(CP_ACP, 0, ffd.cFileName, -1, 0, 0, 0, 0);
char* pcStr = new char[nSize];
WideCharToMultiByte(CP_ACP, 0, ffd.cFileName, -1, pcStr, nSize, 0, 0);
//std::cout << pcStr << "\n";
vsFileList.push_back(std::string(pcStr));
delete[] pcStr;
} while (FindNextFile(hFind, &ffd) != 0);
}
int main()
{
// watch the foo directory for new files
std::string sDir = "C:\\foo";
std::vector<std::string> vsOldFileList, vsNewFileList;
GetCurrentFilesInDir(sDir, vsOldFileList);
std::wstring wStr = std::wstring(sDir.begin(), sDir.end());
LPCWSTR lpcwsDir = (LPCWSTR)wStr.c_str();
DWORD dwWaitStatus;
HANDLE dwChangeHandle;
dwChangeHandle = FindFirstChangeNotification(
lpcwsDir,
FALSE,
FILE_NOTIFY_CHANGE_FILE_NAME);
while (TRUE)
{
// returns multiple times before and after new file appears!!
dwWaitStatus = WaitForSingleObject(dwChangeHandle, INFINITE);
switch(dwWaitStatus)
{
case WAIT_OBJECT_0:
GetCurrentFilesInDir(sDir, vsNewFileList);
std::string sNewFileName = FindNewFile(vsNewFileList, vsOldFileList);
std::cout << sNewFileName << "\n";
GetCurrentFilesInDir(sDir, vsOldFileList);
FindNextChangeNotification(dwChangeHandle);
break;
}
}
}
The problem is that, when I save a new file in C:\foo (for instance, using Notepad++ to "Save As" an open .txt file in C:\foo), the call to WaitForSingleObject() in the while loop will return 0 multiple times. Since my FindNewFile() method returns an empty string if there is no new file in the directory, I will get output like:
a.txt
or:
b.txt
Or even:
c.txt
c.txt
Can someone explain what I am missing here?
Using FindNextChangeNotification can not tell you what actually happened, and the operation of the file may involve multiple changes.
You can try to use ReadDirectoryChangesW and here is a sample:
#include <windows.h>
#include <iostream>
using namespace std;
wstring getname(FILE_NOTIFY_INFORMATION* tmp)
{
wstring s = L"";
for (int i = 0; i < tmp->FileNameLength / 2; i++)
s += tmp->FileName[i];
return s;
}
int main(int argc, const char* argv[])
{
HANDLE hDir;
char notify[1024];
DWORD cbBytes;
LPTSTR path;
FILE_NOTIFY_INFORMATION* pnotify = (FILE_NOTIFY_INFORMATION*)notify;
FILE_NOTIFY_INFORMATION* tmp;
// GetCurrentDirectory(MAX_PATH,path.GetBuffer(MAX_PATH+1));
path = (LPTSTR)L"D:\\test";
hDir = CreateFile(path, FILE_LIST_DIRECTORY,
FILE_SHARE_READ |
FILE_SHARE_WRITE |
FILE_SHARE_DELETE, NULL,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS |
FILE_FLAG_OVERLAPPED, NULL);
wcout << L"===CreateFile complete===" << endl;
if (hDir == INVALID_HANDLE_VALUE)
{
wcout << L"invalid handle value" << endl;
return -1;
}
FILE_NOTIFY_INFORMATION buffer[1024];
FILE_NOTIFY_INFORMATION* pbuffer;
while (TRUE)
{
wcout << L"waiting..." << endl;
WaitForSingleObject(hDir, INFINITE);
if (ReadDirectoryChangesW(hDir, &buffer, sizeof(buffer),
TRUE, FILE_NOTIFY_CHANGE_FILE_NAME,
&cbBytes, NULL, NULL))
{
pbuffer = buffer;
do {
tmp = pbuffer;
switch (tmp->Action)
{
case FILE_ACTION_ADDED:
wcout << L"Directory/File added - " << getname(tmp) << endl;
break;
case FILE_ACTION_REMOVED:
wcout << L"Directory/File removed - " << getname(tmp) << endl;
break;
case FILE_ACTION_MODIFIED:
wcout << L"Directory/File modfied - " << getname(tmp) << endl;
break;
case FILE_ACTION_RENAMED_OLD_NAME:
wcout << L"Directory/File old name - " << getname(tmp) << endl;
break;
case FILE_ACTION_RENAMED_NEW_NAME:
wcout << L"Directory/File new name - " << getname(tmp) << endl;
break;
default:
wcout << L"unknown action\n" << endl;
break;
}
pbuffer += pbuffer->NextEntryOffset;
} while (pbuffer->NextEntryOffset);
}
else
{
wcout << "readChangesW failed now return" << endl;
return -1;
}
}
}
When you do the Save As operation, you will find:
Therefore, multiple file operations were triggered when actually saving as, and you also performed multiple comparisons when processing new file comparisons, so empty characters were output.
More reference: FindFirstChangeNotification is notifying about changes twice

SHGetValue returns 2 when querying UAC value

I would like to check the UAC configuration settings of windows. And thus recover the parameters of the UAC in the registry keys.
I used the windows SHGetValue function but the status always returns me 2 without any information.
I use C++11, MinGW and windows.
My code is :
DWORD dwStatus;
LPCSTR pszSubKey= "HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System";
LPCSTR pszValue="";
DWORD pdwType=REG_SZ;
PVOID pvData[63];
DWORD pcbData;
pcbData=sizeof(pvData);
dwStatus=SHGetValueA(HKEY_LOCAL_MACHINE, pszSubKey, pszValue, &pdwType, pvData, &pcbData);
//Here dwStatus = 2
// pvData = 0x11fd0b2
// pcbData = 504
What specific key you are trying to read? I am not an expert on win32 API so I don't know whether there is a way to read a set of keys at once (Edit: I think there areRegEnumValue/RegEnumValueA functions for this purpose). Here is an example that shows how you can read "EnableLUA" or any other key from that path:
#include <windows.h>
#include <iostream>
#include <shlwapi.h>
bool ReadUACRegistryKey(char* key, DWORD &keyValue)
{
LPCTSTR pszSubKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System";
LPCTSTR pszValue = key;
// don't care
DWORD dwType = 0;
DWORD dwValue = 0;
//
DWORD dwValueSize = sizeof(dwValue);
int retval = SHGetValue( HKEY_LOCAL_MACHINE, pszSubKey, key, &dwType, &dwValue, &dwValueSize);
if ( retval != ERROR_SUCCESS)
{
return false;
}
keyValue = dwValue;
return true;
}
int main()
{
DWORD keyValue;
char* key = "EnableLUA"; // "EnableSecureUIAPaths" etc..;
if (ReadUACRegistryKey(key, keyValue))
{
std::cout << "Successfully readed key " << key << ", value:" << keyValue << std::endl;
}
else
{
std::cout << "Unable to read value of key " << key << std::endl;
}
return 0;
}
Also keep in mind that value of read key value is stored in value parameter, not in the return value of the function.
Edit: Answer of the the op's comment "I want use FilterAdministratorToken but is disable by default how give it back enable .?". Keep in mind that your process need to have admin rights to perform these operation.
#include <windows.h>
#include <iostream>
#include <shlwapi.h>
bool ReadUACRegistryKey(char* key, DWORD &keyValue)
{
LPCTSTR pszSubKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System";
LPCTSTR pszValue = key;
// don't care
DWORD dwType = 0;
DWORD dwValue = 0;
//
DWORD dwValueSize = sizeof(dwValue);
int retval = SHGetValue( HKEY_LOCAL_MACHINE, pszSubKey, key, &dwType, &dwValue, &dwValueSize);
if ( retval != ERROR_SUCCESS)
{
return false;
}
keyValue = dwValue;
return true;
}
bool EnableFilterAdministratorToken()
{
// first check if its already enabled or not
DWORD val;
if (ReadUACRegistryKey("FilterAdministratorToken", val))
{
if (val == 1)
{
std::cout << "FilterAdministratorToken is already enabled" << std::endl;
return true;
}
}
else
{
std::cout << "Unable to read key" << std::endl;
return false;
}
// its not enabled, we need to enable it manually
// obtain a handle to reg key
HKEY hKey;
int retval = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", 0, KEY_SET_VALUE, &hKey);
if (retval != ERROR_SUCCESS)
{
// we are unable to obtain a handle to reg key
std::cout << "Unable to obtain handle to reg key" << std::endl;
return false;
}
DWORD enabledValue = 1;
retval = RegSetValueExA(hKey, "FilterAdministratorToken", 0, REG_DWORD, (BYTE*) &enabledValue, sizeof(DWORD));
if (retval != ERROR_SUCCESS)
{
// some error occured
std::cout << "Some error occured during setting the key value" << std::endl;
RegCloseKey(hKey);
return false;
}
std::cout << "Successfully changed key value" << std::endl;
RegCloseKey(hKey);
return true;
}
int main()
{
if (EnableFilterAdministratorToken())
{
std::cout << "OK" << std::endl;
}
else
{
std::cout << "FAIL" << std::endl;
}
return 0;
}

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.

Problems with DLL Injector

I have recently been learning C++ and I am at the stage where I can build sufficient enough programs.
At the moment I am just trying to inject ONE DLL into a process of my choice, I am having trouble because when it injects it works fine, but when I don't have the DLL it still acts as if it injected.
Help please.
My Source:
#include <iostream>
#include <Windows.h>
#include <TlHelp32.h>
using namespace std;
bool InjectDLL(DWORD ProcessID);
char FileToInject[] = "DLL.dll";
char ProcessName[] = "ac_client.exe";
typedef HINSTANCE (*fpLoadLibrary)(char*);
int main()
{
DWORD processId = NULL;
PROCESSENTRY32 pe32 = {sizeof(PROCESSENTRY32)};
HANDLE hProcSnap;
while(!processId)
{
system("CLS");
cout << "|Coded by Proton|" << endl;
cout << "Waiting for AssaultCube ..." << endl;
hProcSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if(Process32First(hProcSnap, &pe32))
{
do
{
if(!strcmp(pe32.szExeFile, ProcessName))
{
processId = pe32.th32ProcessID;
break;
}
}
while(Process32Next(hProcSnap, &pe32));
}
Sleep(1000);
}
while(!InjectDLL(processId))
{
system("CLS");
cout << "DLL failed to inject." << endl;
Sleep(1000);
}
cout << "DLL Injected." << endl << endl;
cout << "Closing Injector in 5 seconds ..." << endl;
CloseHandle(hProcSnap);
Sleep(5000);
return 0;
}
bool InjectDLL(DWORD ProcessID)
{
HANDLE hProc;
LPVOID paramAddr;
HINSTANCE hDll = LoadLibrary("KERNEL32");
fpLoadLibrary LoadLibraryAddr = (fpLoadLibrary)GetProcAddress(hDll, "LoadLibraryA");
hProc = OpenProcess (PROCESS_ALL_ACCESS, false, ProcessID);
char dllPath[250] = "C:\\";
strcat(dllPath, FileToInject);
paramAddr = VirtualAllocEx(hProc, 0, strlen(dllPath)+1, MEM_COMMIT, PAGE_READWRITE);
bool memoryWritten = WriteProcessMemory(hProc, paramAddr, dllPath, strlen(dllPath)+1, NULL);
CreateRemoteThread(hProc, 0, 0, (LPTHREAD_START_ROUTINE)LoadLibraryAddr, paramAddr, 0, 0);
CloseHandle(hProc);
return memoryWritten;
}
Thanks so much!
Don't ignore the return value from CreateRemoteThread.
Use the thread handle to check if it stays running (WaitForSingleObject with a timeout), and if it exited, check its return code.