Windows SetupAPI DIF_REMOVE usage - c++

I'm trying to entirely disable the keyboard using the windows SetupAPI.
At present I can remove the keyboard successfully with no issues using the DIF_REMOVE function like so:
#include <windows.h>
#include <SetupAPI.h>
#include <iostream>
#include <string>
const std::string keyboard_device_instance_path("<my_path_here>"); // Win7
HDEVINFO DeviceInfoSet = ::SetupDiGetClassDevs(nullptr, nullptr, nullptr, DIGCF_ALLCLASSES | DIGCF_ALLCLASSES);
SP_DEVINFO_DATA DeviceInfoData;
::ZeroMemory(&DeviceInfoData, sizeof(SP_DEVINFO_DATA));
DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
DWORD DeviceIndex = 0;
std::vector<char> DeviceInstanceId(128, '\0');
DWORD RequiredSize = 0;
// Query all devices
while (::SetupDiEnumDeviceInfo(DeviceInfoSet, DeviceIndex++, &DeviceInfoData))
{
// Find the Keyboard
if (::SetupDiGetDeviceInstanceIdA(DeviceInfoSet, &DeviceInfoData, &DeviceInstanceId[0], DWORD(DeviceInstanceId.size()), &RequiredSize))
{
if (keyboard_device_instance_path == &DeviceInstanceId[0])
{
std::cout << "Breaking keyboard\n";
if (!SetupDiCallClassInstaller(DIF_REMOVE, DeviceInfoSet, &DeviceInfoData))
{
std::cerr << "Failed to remove keyboard: " << ::GetLastError() << '.' << std::endl;
}
}
After disabling it, I want to re-enable the keyboard when a condition is met. For this I naturally looked to 'DIF_UNREMOVE' but have had no success.
Here is the code that attempts to re-enable the keyboard:
SP_UNREMOVEDEVICE_PARAMS UnRemoveParams;
UnRemoveParams.ClassInstallHeader.cbSize = sizeof(SP_CLASSINSTALL_HEADER);
UnRemoveParams.ClassInstallHeader.InstallFunction = DIF_UNREMOVE;
UnRemoveParams.Scope = DI_UNREMOVEDEVICE_CONFIGSPECIFIC;
UnRemoveParams.HwProfile = 0;
if (::SetupDiSetClassInstallParams(DeviceInfoSet, &DeviceInfoData, &UnRemoveParams.ClassInstallHeader, sizeof(UnRemoveParams)))
{
std::cout << "Fixing keyboard\n";
if (!SetupDiCallClassInstaller(DIF_UNREMOVE, DeviceInfoSet, &DeviceInfoData))
{
std::cerr << "Failed to re-enable keyboard: " << ::GetLastError() << std::endl;
}
}
This code is used in the while loop immediately after the removal code. I get an error "No such device installed". What is the correct way to do this? I can only use headers supported by windowsXP

I eventually solved this by instead re-enumerating the systems hardware devices like so:
DWORD pdnDevInst = 0;
if (CM_Locate_DevNodeA(PDEVINST(&pdnDevInst), NULL, CM_LOCATE_DEVNODE_NORMAL) != CR_SUCCESS)
{
std::cout << "Failed to revive keyboard\n";
}
else if (CM_Reenumerate_DevNode(pdnDevInst, CM_REENUMERATE_NORMAL) != CR_SUCCESS)
{
std::cout << "Failed to revive keyboard: Renumerate dev node Error\n";
}

Related

How do I get the value from a memory address from Cheat engine using Win32's ReadProcessMemory?

I am trying to change the value of minerals in Starcraft II to learn win32.
I am not into gaming at all. but chose my childhood game to leearn win32 and operating systems.
Here is my code.
everything works, I can get the handle and its process id.
however reading the value does not work.
From cheat engine, I can change the value of minerals to whatever I like.
Here is the memory address of the minerals.
#include <iostream>
#include <Windows.h>
using namespace std;
int main()
{
int newMineral = 2000;
int readMineral = 0;
HWND hwnd = FindWindowA(NULL, "Brood War");
if (hwnd == NULL)
{
cout << "Cannot find window." << endl;
Sleep(30000);
exit(-1);
}
else
{
DWORD procID;
GetWindowThreadProcessId(hwnd, &procID);
HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, procID);
if (procID == NULL)
{
cout << "Cannot find procssID." << endl;
Sleep(30000);
exit(-1);
}
else
{
cout << "process exists." << endl;
cout << procID << endl;
//WriteProcessMemory(handle, (LPVOID)0x57F0F0, &newMineral, sizeof(newMineral), 0);
ReadProcessMemory(handle, (PBYTE*)0x57F0F0, &readMineral, sizeof(int), 0);
cout << readMineral << endl;
}
}
return 0;
I think it is the format of my memory address maybe since the handle and processID are obtainable.

How can I read and write to pipes created for a child process in c++

I am making a tester program that opens a console application and reads it's standard input writes to it's standard output, but am having issues with the pipes. I am using named pipes since I might have to run this threaded or even open multiple executables to communicate with at once. These will need to remain running and continuously take input and give out put, as in a console calculator that asks if you if you want another calculation or to exit after each calculation.
Using error checking I have found that The pipes are created successfully, I apply them to the startupInfo struct and successfully open the executable. A note here, if I set a break point in visual studio just after the call to createProcess, the child process does show up in my task manager, the check STILL_ACTIVE is true and peaking at the pipe reveals an empty pipe. If no break point is set then I don't see it, and the check STILL_ACTIVE is false.
To simplify the problem I went back to basics, a simple hello world executable in c++. The calculator will be the next test. This prints hello world to the console and via a cin:get() waits for the enter key to be pressed. I ran this with the tester and tried to read the "Hello World" from the child process. I get nothing.
The end project will be open source, I don't want the user to have to download any other libraries to compile the project, and Boost::Process actually requires 2 install since process is not standard yet.
I know that I am close, here is my simple tester as one file with the process class extracted to be inline in the main. Note: I have enabled c++20 in my compiler.
// Tester.cpp
#include <string>
#include <string_view>
#include <vector>
#include <iostream>
#include <fstream>
#include <filesystem>
#include <io.h>
#include <fcntl.h>
#include <windows.h>
int main()
{
std::string data = "";
int id = 1;
std::string executable = "HelloWorld.exe";
if (_access((executable).c_str(), 0) != -1)
{
std::cerr << "Error: Executable file not found: " << executable << std::endl;
exit(0);
}
SECURITY_ATTRIBUTES saAttr{};
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
//Pipe names
std::wstring pipeErr = L"\\\\.\\pipe\\err_" + std::to_wstring(id);
std::wstring pipeOut = L"\\\\.\\pipe\\out_" + std::to_wstring(id);
std::wstring pipeIn = L"\\\\.\\pipe\\in_" + std::to_wstring(id);
// The Child error pipe for reading
CreateNamedPipeW(pipeErr.c_str(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, 1, 1024, 1024, 0, NULL);
HANDLE err_pipe = CreateFileW(pipeErr.c_str(), GENERIC_READ | GENERIC_WRITE, 0, &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
// The Child out pipe for reading
CreateNamedPipeW(pipeOut.c_str(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, 1, 1024, 1024, 0, NULL);
HANDLE out_pipe = CreateFileW(pipeOut.c_str(), GENERIC_READ | GENERIC_WRITE, 0, &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
// The Child in pipe for writing
CreateNamedPipeW(pipeIn.c_str(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, 1, 1024, 1024, 0, NULL);
HANDLE in_pipe = CreateFileW(pipeIn.c_str(), GENERIC_READ | GENERIC_WRITE, 0, &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
if (in_pipe == INVALID_HANDLE_VALUE || out_pipe == INVALID_HANDLE_VALUE || err_pipe == INVALID_HANDLE_VALUE)
{
std::cout << "Error Creating Handles, Code: " << GetLastError() << std::endl;
return 0;
}
// Make sure the handles' inheritance is set correctly
if (!SetHandleInformation(in_pipe, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT) ||
!SetHandleInformation(out_pipe, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT) ||
!SetHandleInformation(err_pipe, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT))
{
std::cerr << "Error: Failed to set handle information for the child process" << std::endl;
return 0;
}
// Set up the startup info struct
STARTUPINFOA startupInfo;
memset(&startupInfo, 0, sizeof(startupInfo));
startupInfo.cb = sizeof(STARTUPINFOA);
startupInfo.hStdInput = in_pipe;
startupInfo.hStdOutput = out_pipe;
startupInfo.hStdError = err_pipe;
startupInfo.dwFlags |= STARTF_USESTDHANDLES;
// Set up the process info struct
PROCESS_INFORMATION processInfo;
memset(&processInfo, 0, sizeof(processInfo));
// Create the child process
if (CreateProcessA(NULL, executable.data(), NULL, NULL, TRUE, 0, NULL, NULL, &startupInfo, &processInfo) == 0)
{
std::cerr << "Error: Failed to create the child process" << std::endl;
return 0;
}
// Set the pipes to non-blocking mode
DWORD mode = PIPE_NOWAIT;
SetNamedPipeHandleState(out_pipe, &mode, NULL, NULL);
SetNamedPipeHandleState(err_pipe, &mode, NULL, NULL);
SetNamedPipeHandleState(in_pipe, &mode, NULL, NULL);
Sleep(500); //wait for child to start, may not be neccesary
// Get the exit code of the child process
DWORD exitCode;
GetExitCodeProcess(processInfo.hProcess, &exitCode);
if (exitCode == STILL_ACTIVE) {
// Set up the read buffer
char buffer[1024];
memset(buffer, 0, sizeof(buffer));
DWORD bytesRead = 0;
DWORD bytesAvail = 0;
// Check if there is data available to read from the pipe
if (!PeekNamedPipe(out_pipe, buffer, sizeof(buffer), &bytesRead, &bytesAvail, NULL)) {
std::cerr << "PeekNamedPipe failed (" << GetLastError() << ").\n";
return 0;
}
if (bytesAvail == 0)
{
std::cerr << "Pipe is empty" << std::endl;
}
if (!ReadFile(out_pipe, buffer, sizeof(buffer) - 1, &bytesRead, NULL))
{
std::cerr << "Failed to read from pipe. Error code: " << GetLastError() << std::endl;
return 0;
}
data = buffer;
}
if (data == "") {
std::cout << "Something went wrong. Code: " << GetLastError() << std::endl;
}
else {
std::cout << data << std::endl;
}
std::cout << "Press any key." << std::endl;
std::cin.get();
return 0;
}
and, for reference, here is helloworld.exe:
// HelloWorld.cpp
#include <iostream>
int main()
{
std::cout << "Hello World!" << std::endl;
std::cin.get();
}
Thanks to #Igor Tandetnik!
Here is the working Tester.cpp:
// Tester.cpp
#include <string>
#include <string_view>
#include <vector>
#include <iostream>
#include <fstream>
#include <filesystem>
#include <io.h>
#include <fcntl.h>
#include <windows.h>
#include <aclapi.h>
constexpr auto BUFSIZE = 4096;
int main()
{
std::string data = "";
int id = 1;
std::wstring executable = L"HelloWorld.exe";
std::wstring argv = L"";
std::string name_c = "";
std::string path_c = "";
HANDLE hChildStd_IN_Rd = NULL;
HANDLE hChildStd_IN_Wr = NULL;
HANDLE hChildStd_OUT_Rd = NULL;
HANDLE hChildStd_OUT_Wr = NULL;
HANDLE hChildStd_ERR_Rd = NULL;
HANDLE hChildStd_ERR_Wr = NULL;
size_t size;
wcstombs_s(&size, nullptr, 0, executable.c_str(), executable.length());
name_c.resize(size);
wcstombs_s(&size, name_c.data(), name_c.size(), executable.c_str(), executable.length());
wchar_t current_dir[FILENAME_MAX];
if (_wgetcwd(current_dir, FILENAME_MAX) == nullptr) {
std::cerr << "Error getting current working directory. Code:" << GetLastError() << std::endl;
exit(0);
}
wchar_t path_exe[MAX_PATH];
GetModuleFileName(NULL, path_exe, MAX_PATH);
std::wstring path = path_exe;
path = std::filesystem::path(path).parent_path();
path += L"\\";
path += executable;
wcstombs_s(&size, nullptr, 0, path.c_str(), path.length());
path_c.resize(size);
wcstombs_s(&size, path_c.data(), path_c.size(), path.c_str(), path.length());
int found = _waccess_s(path.c_str(), 0);
if (found != 0)
{
std::cerr << "Error: Executable file not found: " << name_c << std::endl;
exit(0);
}
SECURITY_ATTRIBUTES sa_attr{};
sa_attr.nLength = sizeof(SECURITY_ATTRIBUTES);
sa_attr.bInheritHandle = TRUE;
sa_attr.lpSecurityDescriptor = NULL;
// Create the pipes
if (!CreatePipe(&hChildStd_OUT_Rd, &hChildStd_OUT_Wr, &sa_attr, 0)
|| !CreatePipe(&hChildStd_IN_Rd, &hChildStd_IN_Wr, &sa_attr, 0)
|| !CreatePipe(&hChildStd_ERR_Rd, &hChildStd_ERR_Wr, &sa_attr, 0)) {
std::cout << "Error Creating Pipes, Code: " << GetLastError() << std::endl;
return 1;
}
if (hChildStd_OUT_Rd == INVALID_HANDLE_VALUE || hChildStd_OUT_Wr == INVALID_HANDLE_VALUE
|| hChildStd_IN_Rd == INVALID_HANDLE_VALUE || hChildStd_IN_Wr == INVALID_HANDLE_VALUE
|| hChildStd_ERR_Rd == INVALID_HANDLE_VALUE || hChildStd_ERR_Wr == INVALID_HANDLE_VALUE)
{
std::cout << "Error Creating Handles, Code: " << GetLastError() << std::endl;
return 1;
}
// Set up the startup info struct
STARTUPINFOW startup_info;
ZeroMemory(&startup_info, sizeof(STARTUPINFOW));
startup_info.cb = sizeof(STARTUPINFOW);
startup_info.hStdOutput = hChildStd_OUT_Wr;
startup_info.hStdError = hChildStd_ERR_Wr;
startup_info.hStdInput = hChildStd_IN_Rd;
startup_info.dwFlags |= STARTF_USESTDHANDLES;
// Set up the process info struct
PROCESS_INFORMATION process_info;
memset(&process_info, 0, sizeof(process_info));
// Create the child process
if (!CreateProcess(path.data(), NULL, &sa_attr, NULL, TRUE, 0, NULL, NULL, &startup_info, &process_info))
{
std::cerr << "Error: Failed to create the child process. Code: " << GetLastError() << std::endl;
return 1;
}
// Get the exit code of the child process
DWORD exitCode;
GetExitCodeProcess(process_info.hProcess, &exitCode);
if (exitCode != STILL_ACTIVE) {
std::wcout << "Unable to Start Process: " << executable.c_str() << std::endl;
return 1;
}
std::wcout << "Started Process: " << executable.c_str() << std::endl;
Sleep(500); //wait for child to start, may not be neccesary
// Get the exit code of the child process
GetExitCodeProcess(process_info.hProcess, &exitCode);
if (exitCode == STILL_ACTIVE) {
// Set up the read buffer
DWORD bytesRead{}, dwWritten{};
CHAR buffer[BUFSIZE]{};
BOOL bSuccess = FALSE;
HANDLE hParentStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
bSuccess = ReadFile(hChildStd_OUT_Rd, buffer, BUFSIZE, &bytesRead, NULL);
if (!bSuccess || bytesRead == 0)
{
std::cerr << "Failed to read from pipe. Error code: " << GetLastError() << std::endl;
return 1;
}
std::vector<char> v_data(buffer, buffer + bytesRead);
data = std::string(v_data.data(), v_data.size());
}
std::cout << "Recieved from Child: " << data << std::endl;
if (data == "") {
std::cout << "Something went wrong. Code: " << GetLastError() << std::endl;
return 1;
}
else {
std::cout << data << std::endl;
}
CloseHandle(process_info.hThread);
std::cout << "Press any key." << std::endl;
std::cin.get();
return 0;
}

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

Windows Registry Monitoring for change using C++

I have following piece of code that is working on the following steps:
Open the RegistryKey using RegOpenKeyEx
After opening key, Create a event using CreateEvent.
Using RegNotifyChangeKeyValue for getting Notification.
The above steps only gives me a notification of change occured but not the information on where the change occured. eg consider following code:
#include <Windows.h>
#include <iostream>
#include <string>
int main()
{
DWORD dwFilter = REG_NOTIFY_CHANGE_NAME|
REG_NOTIFY_CHANGE_ATTRIBUTES |
REG_NOTIFY_CHANGE_LAST_SET |
REG_NOTIFY_CHANGE_SECURITY;
HKEY pHresult=0;
if(RegOpenKeyEx(HKEY_LOCAL_MACHINE,"SOFTWARE\\aaaa",0,KEY_NOTIFY|KEY_CREATE_SUB_KEY|KEY_ENUMERATE_SUB_KEYS|KEY_QUERY_VALUE|KEY_WOW64_64KEY,&pHresult)!=ERROR_SUCCESS){
std::cout << "FAIL IN OPEN SOFTWARE" << std::endl;
}
std::cout << " OPEN software//aaaa" << std::endl;
while(1)
{
HANDLE hevent = CreateEvent(NULL,FALSE, TRUE, NULL);
if(RegNotifyChangeKeyValue(pHresult,TRUE,dwFilter,hevent,TRUE) != ERROR_SUCCESS)
{
std::cout << "NOTIFICATION FAILED " << std::endl;
}
DWORD dwret = WaitForSingleObject(hevent, 2000);
if(dwret == WAIT_TIMEOUT)
{
std::cout << " TIMEOUT " << std::endl;
}
else if (dwret == WAIT_FAILED)
{
//
}
else
{
std::cout << "Change Occured" << std::endl;
}
//Sleep(2000);
}
RegCloseKey(pHresult);
}
In above code, if change is done in aaaa, i get Change Occured. How do I get the location where the change occured. One way would be using recursion and scanning the whole path. Is there any better way or API for reducing the overhead of recursion way?

How to Enumerate Names of All Named Pipes in a Process?

I need to open a certain named pipe so I can fuzz test it, however my test code does not have access to the same data used to generate the name of the named pipe. However I can recognize the name of the pipe and then use that name to open up the pipe for fuzzing.
I used this forum post to start enumerating names of the handles on the system:
http://forum.sysinternals.com/howto-enumerate-handles_topic18892.html
However it seems that won't work with named pipes for some reason.
TL;DR: What API(s) do I need to use to list the names of all named pipes in the current process on Windows?
This will enumerate all named pipes in the system, or at the very least put you a step in the right direction.
This works in MinGW when built with -fpermissive. It should work with similar settings in MSVC.
#ifndef _WIN32_WINNT
// Windows XP
#define _WIN32_WINNT 0x0501
#endif
#include <Windows.h>
#include <Psapi.h>
// mycreatepipeex.c is at http://www.davehart.net/remote/PipeEx.c
// I created a simple header based on that.
#include "mycreatepipeex.h"
#include <iostream>
#include <cstdio>
#include <errno.h>
void EnumeratePipes()
{
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
#define TARGET_PREFIX "//./pipe/"
const char *target = TARGET_PREFIX "*";
memset(&FindFileData, 0, sizeof(FindFileData));
hFind = FindFirstFileA(target, &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
std::cerr << "FindFirstFileA() failed: " << GetLastError() << std::endl;
return;
}
else
{
do
{
std::cout << "Pipe: " << TARGET_PREFIX << FindFileData.cFileName << std::endl;
}
while (FindNextFile(hFind, &FindFileData));
FindClose(hFind);
}
#undef TARGET_PREFIX
return;
}
int main(int argc, char**argv)
{
HANDLE read = INVALID_HANDLE_VALUE;
HANDLE write = INVALID_HANDLE_VALUE;
unsigned char pipe_name[MAX_PATH+1];
BOOL success = MyCreatePipeEx(&read, &write, NULL, 0, 0, 0, pipe_name);
EnumeratePipes();
if ( success == FALSE )
{
std::cerr << "MyCreatePipeEx() failed: " << GetLastError() << std::endl;
return 1;
}
FILE *f = fopen((const char*)pipe_name, "rwb");
if ( f == NULL )
{
std::cerr << "fopen(\"" << pipe_name << "\") failed: " << (int)errno << std::endl;
}
CloseHandle(read);
CloseHandle(write);
return 0;
}