WinApi Thread (Pointer error) - c++

I have a probelm :( i wanna make a program wich gives a random number :) i don't want use rand() function :) i wanna make one for me then turn it to a function ;) for educational purpose :)
but i have a problem :( see my code :)
#include <stdio.h>
#include <iostream>
#include <conio.h>
#include <windows.h>
#define MIN 0
#define MAX 99999
using namespace std;
typedef struct _RANDOM_INFO{
DWORD random;
DWORD min;
DWORD max;
} RANDOM_INFO, * LPRANDOM_INFO;
void Error(LPSTR lpErrorMessage){
cout << lpErrorMessage << endl;
exit(EXIT_FAILURE);
}
void GetRandom(LPVOID lpParam){
DWORD dwListSize = 10000, min = 0, max = 99999;
LPDWORD lpRandom = (LPDWORD)lpParam;
LPSTR lpFileSelf, lpKernel, lpNtdll;
HMODULE hFileSelf = NULL, hKernel = NULL, hNtdll = NULL;
hFileSelf = (HMODULE) GetModuleHandle(NULL);
hKernel = (HMODULE) GetModuleHandle("kernel.dll");
hNtdll = (HMODULE) GetModuleHandle("ntdll.dll");
lpFileSelf = (LPSTR) hFileSelf;
lpKernel = (LPSTR) hKernel;
lpNtdll = (LPSTR) hNtdll;
while(1){
DWORD i;
for(i = 0; i <= dwListSize; i++){
*lpRandom = (DWORD)lpFileSelf[i];
}
i = 0;
}
return;
}
int main(int argc, char **argv)
{
DWORD random = 0;
DWORD getRandomThreadId = 0;
HANDLE hGetRandomThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)GetRandom, &random, 0, &getRandomThreadId);
if(hGetRandomThread == INVALID_HANDLE_VALUE)
Error("Cannot make a random list.");
getch();
cout << random << endl;
Sleep(1500);
return 0;
}
The variable should get a value when and print it but i always i get 0 and a windows error can someone tell me why??? and another problem when i try to use the variable hKernel in the GetRandom function i get an error too :( but it works fine whith hFileSelf and hNtdll !!!! is kernel protected from reading???
Note : this is not a random number generation :) its just a way to get a number from the memory when the user click on the enter on his keyboard :), and its not always the same time for all users so its not always the same pointer in memory :) i hope u understand what i want do :) sorry for my bad englush :) just help me to fix the problem :)
Thank u :)

Your GetRandom() function does not have the correct signature for a CreateThread() callback procedure. Try this instead:
#include <stdio.h>
#include <iostream>
#include <conio.h>
#include <windows.h>
#define MIN 0
#define MAX 99999
using namespace std;
typedef struct _RANDOM_INFO
{
DWORD random;
DWORD min;
DWORD max;
} RANDOM_INFO, * LPRANDOM_INFO;
void Error(LPSTR lpErrorMessage)
{
cout << lpErrorMessage << endl;
exit(EXIT_FAILURE);
}
HMODULE hFileSelf = (HMODULE) GetModuleHandle(NULL);
DWORD WINAPI GetRandomThreadProc(LPVOID lpParam)
{
LPDWORD lpRandom = (LPDWORD) lpParam;
DWORD dwListSize = 10000, min = 0, max = 99999;
LPBYTE lpFileSelf = (LPBYTE) hFileSelf;
while (1)
{
for (DWORD i = 0; i <= dwListSize; ++i)
{
*lpRandom = (DWORD) lpFileSelf[i];
}
Sleep(0);
}
return 0;
}
int main(int argc, char **argv)
{
DWORD dwRandom = 0;
DWORD dwRandomThreadId = 0;
HANDLE hGetRandomThread = CreateThread(NULL, 0, &GetRandomThreadProc, &dwRandom, 0, &dwRandomThreadId);
if (hGetRandomThread == INVALID_HANDLE_VALUE)
Error("Cannot make a random list.");
do
{
getch();
cout << dwRandom << endl;
}
while (WaitForSingleObject(hGetRandomThread, 0) == WAIT_TIMEOUT);
CloseHandle(hGetRandomThread);
return 0;
}

i wanna make a program wich gives a random number
What you are doing has nothing to do with random number generation.
This is one way to do it:
Linear Congruential Generator

Related

Getting all services and their path to exe

Get list of windows services and print name, status, path to exe
the above statement needs to be solved, I am aware we enum services to find.....since I am beginner ,I don't understand how to retrieve all the path to exe.
this is what I knew
#include <Windows.h>
#include <iostream>
int main()
{
SC_HANDLE sHandle;
LPQUERY_SERVICE_CONFIG lpServiceConfig = NULL;
DWORD cbBufSize = 100;
LPDWORD bytesNeeded = NULL;
sHandle = OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);
sHandle = OpenService(sHandle, "YOU SERVICE NAME",SERVICE_ALL_ACCESS);
QueryServiceConfig(sHandle,lpServiceConfig,cbBufSize,bytesNeeded);
std::cout << lpServiceConfig->lpBinaryPathName << std::endl;
}
You need to use EnumServiceStatus() to query which services are installed. You can then open each service to query its EXE path.
Also, your code is leaking resources and memory.
Try something more like this:
#include <Windows.h>
#include <iostream>
#include <vector>
int main()
{
DWORD bytesNeeded = 0;
DWORD numServices = 0;
DWORD resumeHandle = 0;
SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ENUMERATE_SERVICE);
if (!hSCManager) ...
EnumServicesStatus(hSCManager, SERVICE_WIN32, SERVICE_STATE_ALL, NULL, 0, &bytesNeeded, &numServices, &resumeHandle);
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) ...
std::vector<BYTE> enumBuffer(bytesNeeded);
LPENUM_SERVICE_STATUS pEnum = reinterpret_cast<LPENUM_SERVICE_STATUS>(enumBuffer.data());
if (!EnumServicesStatus(hSCManager, SERVICE_WIN32, SERVICE_STATE_ALL, pEnum, bytesNeeded, &bytesNeeded, &numServices, &resumeHandle)) ...
for(DWORD idx = 0; idx < numServices; ++idx)
{
std::cout << pEnum[idx].lpServiceName << " (" << pEnum[idx].lpDisplayName << ")" << std::endl;
// use/display pEnum[idx].ServiceStatus as needed ...
SC_HANDLE hService = OpenService(hSCManager, pEnum[idx].lpServiceName, SERVICE_QUERY_CONFIG);
if (!hService) ...
QueryServiceConfig(hSerivce, NULL, 0, &bytesNeeded);
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) ...
std::vector<BYTE> configBuffer(bytesNeeded);
LPQUERY_SERVICE_CONFIG lpServiceConfig = reinterpret_cast<LPQUERY_SERVICE_CONFIG>(configBuffer.data());
if (!QueryServiceConfig(hSerivce, lpServiceConfig, bytesNeeded, &bytesNeeded)) ...
std::cout << lpServiceConfig->lpBinaryPathName << std::endl;
CloseServiceHandle(hService);
}
CloseServiceHandle(hSCManager);
}

make a hwid login in c++ (mulitbyte)

hello guys i tried to make a hwid login for a app. The problem is when i compile all the code i have this error.
Error C2676 binary '==': 'std::basic_string,std::allocator>' does not define this operator or a conversion to a type acceptable to the predefined operator
#include <Windows.h>
#include <iostream>
#include <tchar.h>
#include <intrin.h>
#include <TlHelp32.h>
#include <algorithm>
#include <vector>
using namespace std;
vector<string> serial;
vector<string> windows;
void loadserial()
{
serial.push_back("1731602307");
}
void loadWindows()
{
windows.push_back("29548");
}
int main()
{
TCHAR volumeName[MAX_PATH + 1] = { 0 };
TCHAR fileSystemName[MAX_PATH + 1] = { 0 };
DWORD serialNumber = 0;
DWORD maxComponentLen = 0;
DWORD fileSystemFlags = 0;
if (GetVolumeInformation(
_T("C:\\"),
volumeName,
ARRAYSIZE(volumeName),
&serialNumber,
&maxComponentLen,
&fileSystemFlags,
fileSystemName,
ARRAYSIZE(fileSystemName)))
{
}
int cpuinfo[4] = { 0, 0, 0, 0 };
__cpuid(cpuinfo, 0);
char16_t hash = 0;
char16_t* ptr = (char16_t*)(&cpuinfo[0]);
for (char32_t i = 0; i < 8; i++)
hash += ptr[i];
while (true)
{
if (find(serial.begin(), serial.end(), serialNumber) != serial.end())
{
std::cout << "nice you are in our auth system!!";
}
else
{
std::cout << "you arent in the whitelist ;(";
}
}
return(0);
}
OK, now it's clear
find(serial.begin(), serial.end(), serialNumber)
serial is a vector<string> but serialNumber is a DWORD. You can't use find to look for a DWORD in a vector of strings. I guess you need to convert the DWORD to a string first, or maybe you could change serial to a vector<DWORD>.
And as drescherjm says get into the habit of looking at the output tab for your error messages, it's much more useful than the error list (which for some reason microsoft insist on showing you first).

Loop wregex always return false and high cpu usage around 50%

I have a bunch keyword need to loop to match a wchar_t string.
the string is
5698##$%notepad^&343235/ chrome $56&6556firefox$%#$23
and the keyword is
notepad, chrome, firefox
I try to loop it always return FALSE and when i see cpu usage. it so extensive around 50%.
this the code.
unsigned int i;
wchar_t * keyword[] = {L"chrome", L"notepad", L"firefox");
for (i = 0; i < 3; i++)
{
wchar_t * s = L"5698##$%notepad^&343235/ chrome $56&6556firefox$%#$23";
wcmatch m;
wchar_t regex[MAX_PATH];
swprintf(regex, MAX_PATH, L"%s%s", L".+", keyword[i]);
wregex r(regex);
if (regex_search(s, m, r))
{
cout << "It's found" << endl;
}
else
{
cout << "It's not found" << endl;
}
thsi my real project code. enumerate process and match the process and return bool value.
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <Psapi.h>
#include <string>
#include <regex>
using namespace std;
int main()
{
FILE *pFile;
wchar_t *file = L"d:\\a.txt";
wchar_t line[100][MAX_PATH];
unsigned int a = 0;
if (_wfopen_s(&pFile, file, L"r, ccs = UNICODE") == 0)
{
while (fgetws(line[a], 100, pFile))
{
a++;
}
}
DWORD aProcesses[1024], cbNeeded, cProcesses;
unsigned int i;
if (!EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded))
{
return 1;
}
cProcesses = cbNeeded / sizeof(DWORD);
wchar_t jszProcessName[4096] = { 0 };
for (i = 0; i < cProcesses; i++)
{
if (aProcesses[i] != 0)
{
wchar_t szProcessName[MAX_PATH] = TEXT("Unknown");
DWORD processID = aProcesses[i];
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ,
FALSE, processID);
if (NULL != hProcess)
{
HMODULE hMod;
DWORD cbNeeded;
if (EnumProcessModules(hProcess, &hMod, sizeof(hMod),
&cbNeeded))
{
GetModuleBaseName(hProcess, hMod, szProcessName,
sizeof(szProcessName) / sizeof(TCHAR));
wcsncat_s(jszProcessName,szProcessName , 1000);
}
}
}
}
unsigned int c;
for (c = 0; c < a; c++)
{
wchar_t * s = jszProcessName;
wcmatch m;
wchar_t regex[MAX_PATH];
swprintf(regex, MAX_PATH, L"%s%s", L".+", line[c]);
wregex r(regex);
if (regex_search(s, m, r))
{
cout << "It's found" << endl;
}
else
{
cout << "It's not found" << endl;
}
}
return 0;
}
have your regex keywords separated by | characters:
(notepad|chrome|firefox)
https://regex101.com/r/PAZBbx/1

DirectInput8 Hooking Issue

I'm just beginning with directx/directinput development and I'm running some tests with some code samples I've found online. Anyway, I want to hook an application that uses dinput8 to send my own custom input to the forewindow and I'm working with this base to do it:
// dllmain.cpp : Defines the entry point for the DLL application.
#define _CRT_SECURE_NO_WARNINGS // ignore some warnings...
#define _CRT_NON_CONFORMING_SWPRINTFS // ...
#include "stdio.h"
#include <windows.h>
#include "detours.h"
#include <cstdio>
#include <string>
#include <cstring>
#include <vector>
#include <time.h>
#include "dinput.h"
#pragma comment(lib, "detours.lib")
#pragma comment(lib, "user32.lib")
typedef HRESULT(__stdcall* GetDeviceState_t)(LPDIRECTINPUTDEVICE, DWORD, LPVOID *);
HRESULT __stdcall hkGetDeviceState(LPDIRECTINPUTDEVICE pDevice, DWORD cbData, LPVOID *lpvData);
DWORD Base = 0;
DWORD GetDeviceStateOffset = 0x7670; // This is the offset of GetDeviceState from DInput8.dll
// Open IDA and Import the DInput8.dll, then look in the Functions Table for DirectInput8Create
// There is an Address (1000XXXX or 0CXXXXX) - copy it and save it for later
// Then take a look for CDIDev_GetDeviceState and copy that address too
// Now substract the Address from CDIDev_GetDeviceState from DIrectInput8Create and u'll get your offset
HANDLE tmpHandle = NULL;
HMODULE hModDInput8 = NULL;
DWORD dwGetDeviceState = NULL;
FARPROC dwDirectInput8Create = NULL;
struct MyKeys
{
BYTE Key;
DWORD StartTime;
DWORD TTL;
BOOLEAN isDown;
};
MyKeys KeyBuffer[256];
DWORD WINAPI HookThread();
void add_log(char* format, ...);
void SendKeyDInput(byte DIK_, DWORD time);
GetDeviceState_t pGetDeviceState;
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
add_log("==========LOG START==========");
add_log("DLL Attached");
add_log("Creating Thread...");
tmpHandle = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)&HookThread, 0, 0, 0);
if (!tmpHandle)
{
add_log("ThreadCreation Failed!");
}
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
DWORD WINAPI HookThread()
{
Base = (DWORD)GetModuleHandleA("test.exe");
add_log("Thread Created");
add_log("game.exe Base: %x", Base);
while (!hModDInput8)
{
add_log("Searching dinput8.dll...");
hModDInput8 = GetModuleHandle(L"dinput8.dll");
Sleep(100);
}
add_log("Found dinput8.dll: %x !", hModDInput8);
while (!dwDirectInput8Create)
{
add_log("Searching GetDeviceState...");
dwDirectInput8Create = GetProcAddress(hModDInput8, "DirectInput8Create");
Sleep(100);
}
add_log("Found DirectInput8Create: %x !", dwDirectInput8Create);
dwGetDeviceState = (DWORD)((DWORD)dwDirectInput8Create - GetDeviceStateOffset);
add_log("GetDevicestate is here (DirectInput8Create - %x): %x", GetDeviceStateOffset, dwGetDeviceState);
add_log("Hooking GetDeviceState...");
pGetDeviceState = (GetDeviceState_t)DetourAttach(&(PVOID&)dwGetDeviceState, (PBYTE)hkGetDeviceState);
add_log("Initiate Keyboard Buffer...");
//initiate buffer
for (int i = 0; i < 256; i++)
{
KeyBuffer[i].isDown = false;
KeyBuffer[i].Key = 0;
KeyBuffer[i].StartTime = 0;
KeyBuffer[i].TTL = 0;
}
add_log("Going into Main Loop...");
while (true)
{
if (GetAsyncKeyState(VK_F5) & 1 << 15)
{
// We check the Most Sigificant Bit from VK_F5 (F5) whilst we shifted it with 15 bits to left 1
// and then a small delay so we have enaught time to release the key
add_log("F5 pushed attempting to sendkey");
// Sleep a short time so we have time to release the F5 Key
Sleep(500);
// Now we send a A Key with 1 sec time to our Game
SendKeyDInput(DIK_A, 1000);
}
}
return 0;
}
void SendKeyDInput(byte DIK, DWORD time)
{
KeyBuffer[DIK].Key = DIK;
KeyBuffer[DIK].TTL = time;
KeyBuffer[DIK].StartTime = GetTickCount();
}
HRESULT __stdcall hkGetDeviceState(LPDIRECTINPUTDEVICE lpDevice, DWORD cbData, LPVOID *lpvData)
{
HRESULT hResult = DI_OK;
static BYTE buffer[256];
int key_count = 0;
for (int i = 0; i<256; i++)
{
if (KeyBuffer[i].Key != 0 && KeyBuffer[i].TTL>0 && KeyBuffer[i].StartTime != 0)
{
if (GetTickCount() > KeyBuffer[i].StartTime + KeyBuffer[i].TTL && KeyBuffer[i].isDown)
{
KeyBuffer[i].Key = 0;
KeyBuffer[i].StartTime = 0;
KeyBuffer[i].TTL = 0;
KeyBuffer[i].isDown = false;
buffer[KeyBuffer[i].Key] = 0;
}
else {
KeyBuffer[i].isDown = true;
buffer[KeyBuffer[i].Key] = 0x80;
key_count += 1;
add_log("Sending Key %x for %i milliseconds count: %i", KeyBuffer[i].Key, KeyBuffer[i].TTL, key_count);
}
}
}
if (key_count != 0)
{
cbData = 256;
memcpy(lpvData, buffer, cbData);
}
else {
hResult = pGetDeviceState(lpDevice, cbData, lpvData);
}
return hResult;
}
//Creates a Logfile in the Game Directory
void add_log(char* format, ...)
{
HANDLE filehandle;
DWORD dwReadBytes;
char buffer[2048];
char writebuffer[2048];
va_list args;
va_start(args, format);
vsprintf_s(buffer, format, args);
filehandle = CreateFile(L"Log.txt", GENERIC_WRITE, 0, 0, OPEN_ALWAYS, 0, 0);
SetFilePointer(filehandle, 0, 0, FILE_END);
sprintf_s(writebuffer, 2048, "Log Added: %s\r\n", buffer);
WriteFile(filehandle, writebuffer, strlen(writebuffer), &dwReadBytes, 0);
CloseHandle(filehandle);
}
The only issue in this code is when I attempt to send input, it doesn't go through. I've gotten some help and narrowed down a solution to this, which was: "Try GetDeviceState hk just memset(buffer, 0, size) or SendDeviceData". I've searched around a bit and I've been unable to find more on how to implement this solution and I'm stumped.
Could one of you kind people show me how I could use this information to fix this base? I'd be extremely grateful, thanks.

Why aren't my threads running?

// windows_procon.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <time.h>
#include <windows.h>
#include <process.h>
using namespace std;
HANDLE mutex;
HANDLE emptySlots;
HANDLE filledSlots;
#define BUFFER_SIZE 10
void *producer(void *);
void *consumer(void *);
int produceItem(void);
void printBuffer(void);
int buffer[BUFFER_SIZE];
int head = 0;
int tail = 0;
int _tmain(int argc, _TCHAR* argv[])
{
DWORD prodThrdID, consThrdID;
mutex = CreateMutex(NULL,FALSE,NULL);
emptySlots = CreateSemaphore(NULL,BUFFER_SIZE,BUFFER_SIZE,NULL);
filledSlots = CreateSemaphore(NULL,0,0,NULL);
srand(time(NULL));
_beginthreadex(NULL, 0, (unsigned int(__stdcall *)(void*))producer,
0, 0, (unsigned int *)&prodThrdID);
_beginthreadex(NULL, 0, (unsigned int(__stdcall *)(void*))consumer,
0, 0, (unsigned int *)&consThrdID);
return 0;
}
void *producer(void *n)
{
int item;
for(int i = 0; i <BUFFER_SIZE+5; i++)
{
WaitForSingleObject(emptySlots,INFINITE);
WaitForSingleObject(mutex,INFINITE);
item = produceItem();
//printf("Producing");
cout << "Producing: " << item << endl;
//logfile << "Producing: "<< item << endl;
//fprintf(logfile, "Producing: %d \n", item);
buffer[head] = item;
head = (head + 1) % BUFFER_SIZE;
printBuffer();
ReleaseMutex(mutex);
ReleaseSemaphore(filledSlots,1, NULL);
}
return n;
}
void *consumer(void *n)
{
for(int i = 0; i <BUFFER_SIZE+5; i++)
{
WaitForSingleObject(filledSlots,INFINITE);
//Sleep(500);
WaitForSingleObject(mutex,INFINITE);
cout << "Consuming: " << buffer[tail] << endl;
buffer[tail] = 0;
tail = (tail + 1) % BUFFER_SIZE;
printBuffer();
ReleaseMutex(mutex);
ReleaseSemaphore(emptySlots,1, NULL);
}
return n;
}
int produceItem(void)
{
int x = (rand()%11 + 1);
return x;
}
void printBuffer(void)
{
for(int i = 0; i <BUFFER_SIZE; i++)
{
printf("%d ", buffer[i]);
}
printf("END \n");
}
My program here is supposed to be an algorithm for the producer-consumer problem. I think I have the algorithm correct my only problem is that I'm having trouble getting the threads to run properly. Can someone tell me what the issue is?
You need to wait for the threads you create with _beginthreadex to do their work, as it stands you program will exit immediately after creating them. I haven't looked any further at you logic.
Here is an example.
hThread = (HANDLE)_beginthreadex( NULL, 0, &SecondThreadFunc, NULL, 0, &threadID );
WaitForSingleObject( hThread, INFINITE );