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.
Related
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;
}
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
I am trying to inject a simple dll that creates a MessageBox in the target process. Using a injector from the www works without any issues. However using my own code to inject does not do anything at all (I am using it on notepad.exe)
I compiled both dll and this code as x64 debug in VS2017. Injector is created as Win32 console project.
All the stages in the code passes. I get a handle to the process and also the thread handle is valid. However the GetExitCode returns 0 so it fails all the time but I do not know why?
HANDLE process = OpenProcess(PROCESS_ALL_ACCESS, false, pid);
if (process == NULL)
{
std::cout << "Error opening process." << std::endl;
return false;
}
const char * dllString = "C:\\test.dll";
// load memory for dll
int bytes = sizeof(dllString);
PVOID mem = VirtualAllocEx(process, NULL, sizeof(dllString) + 1, MEM_COMMIT, PAGE_READWRITE);
if (mem == NULL)
{
std::cout << "Unable to allocate mem." << std::endl;
CloseHandle(process);
return false;
}
// write dll path to that location
SIZE_T bytesWritten;
BOOL status = WriteProcessMemory(process, mem, dllString, sizeof(dllString) + 1, &bytesWritten);
if (!status)
{
std::cout << "Writing dll path failed." << std::endl;
VirtualFreeEx(process, mem, sizeof(dllString) + 1, MEM_RELEASE);
CloseHandle(process);
return false;
}
FARPROC loadLibrary = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
HANDLE thread = CreateRemoteThread(process, NULL, NULL, reinterpret_cast<LPTHREAD_START_ROUTINE>(loadLibrary), mem, NULL, NULL);
if (thread == INVALID_HANDLE_VALUE)
{
std::cout << "Unable to create thread in remote process. " << std::endl;
VirtualFreeEx(process, mem, sizeof(dllString) + 1, MEM_RELEASE);
CloseHandle(process);
}
WaitForSingleObject(thread, INFINITE);
DWORD exitCode = 0;
GetExitCodeThread(thread, &exitCode);
if (exitCode != 0)
std::cout << "DLL loaded successfully." << std::endl;
else
std::cout << "DLL loading failed." << std::endl;
CloseHandle(thread);
VirtualFreeEx(process, mem, sizeof(dllString) + 1, MEM_RELEASE);
CloseHandle(process);
return true;
Just solved it myself. Actually a noob issue. sizeof in fact is returning the size of the pointer with is 64bits for x64 and not the length of the string for the memory I needed to allocate. So after changing it to strlen it worked.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
There are probably several post that explain my problem in several ways... But I have been searching in google and stackoverflow searchbox and I didn't found anything. So here I go.
I want to Write in a Process Memory a String Changing it in c++, but I don't even know clearly how it work so..
I have this pointer:
Image of the pointer
Please, can someone help me doing it?
I've tried it but it's not working..
#include <windows.h>
#include <iostream>
int main() {
HWND hWnd = FindWindow(0, "WindowName");
if (hWnd == 0) {
std::cout << "Cannot find window." << std::endl;
}
DWORD pId;
GetWindowThreadProcessId(hWnd, &pId);
HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pId);
DWORD baseAddress = 0x009B03D0;
DWORD offset = 0xA7;
DWORD ptrAddress;
char *newString = "newvalue";
ReadProcessMemory(hProc, (void*)baseAddress, &ptrAddress, sizeof(DWORD), 0);
WriteProcessMemory(hProc, (void*)(ptrAddress + offset), newString, strlen(newString), 0);
std::cout << "Done. " << &ptrAddress << std::endl;
std::getchar();
}
I should get the pointer and jumpt to the last one because I only have one offset.. But I'm not getting the correct one..
Edit:
Here is my new code, it works until the WriteProcessMemory function.. What can be wrong?
CODE THAT ACTUALLY WORKS:
int main()
{
unsigned long Pointer; /* to hold the final value */
unsigned long temp; /* hold the temp values */
unsigned long address = 0x009B03D0;
unsigned long offset = 0xA7;
unsigned long newString = 0;
DWORD pid;
HWND hwnd;
hwnd = FindWindow(0, TEXT("NewWindow"));
if (!hwnd)
{
cout << "No!\n";
cin.get();
}
else
{
GetWindowThreadProcessId(hwnd, &pid);
HANDLE phandle = OpenProcess(PROCESS_ALL_ACCESS, 0, pid);
if (!phandle)
{
cout << "None!\n";
cin.get();
}
else
{
while (1)
{
ReadProcessMemory(phandle, reinterpret_cast<LPVOID>(address), &temp, sizeof(temp), 0);
Pointer = temp + offset;
//Good
ReadProcessMemory(phandle, reinterpret_cast<LPVOID>(Pointer), &newString, 16, 0);
cout << reinterpret_cast<LPVOID>(Pointer) << " en " << newString;
Sleep(1000);
}
return 0;
}
}
}
CODE THAT NOT WORK:
int main()
{
unsigned int Pointer; /* to hold the final value */
unsigned int temp; /* hold the temp values */
unsigned int address = 0x009B03D0;
unsigned int offset = 0xA7;
unsigned int newString = 1768060259;
DWORD pid;
HWND hwnd;
hwnd = FindWindow(0, TEXT("NewWindow"));
if (!hwnd)
{
cout << "NO\n";
cin.get();
}
else
{
GetWindowThreadProcessId(hwnd, &pid);
HANDLE phandle = OpenProcess(PROCESS_ALL_ACCESS, 0, pid);
if (!phandle)
{
cout << "NONE\n";
cin.get();
}
else
{
while (1)
{
ReadProcessMemory(phandle, reinterpret_cast<LPVOID>(address), &temp, sizeof(temp), 0);
Pointer = temp + offset;
//Good
if (!WriteProcessMemory(phandle, reinterpret_cast<LPVOID>(Pointer), &newString, sizeof(newString), 0))
std::cerr << "Couldn't write process memory:" << GetLastError() << std::endl;
cout << reinterpret_cast<LPVOID>(Pointer) << " en " << newString;
Sleep(1000);
}
return 0;
}
}
}
Each process has its own memory and address space. So ReadProcessMemory() and WriteProcessMemory() use an intermediary buffer to do their job of accessing memory of another process.
Unfortunately, there are issues with your ReadProcessMemory() call:
you don't initialise ptrAddress to point to a buffer
you pass the address of ptrAddress and not its value that should point to a valid buffer
you pass 0 (i.e. a nullptr) instead of passing the address of the zie variable that should contain the number of bytes that could be read.
Note also that you manage the address in the target process using a DWORD for a LPCVOID. The first is always 32 bits, while the latter depend on your compiling options (32 bit code or 64 bit code).
You should also verify the error code in case of failure. It is almost certain taht special priviledges are required to read/write in distinct processes.
Here an adjusted code, with some diagnosis messages to help you further.
HWND hWnd = FindWindow(0, TEXT("WindowName") );
if (hWnd == 0) {
std::cerr << "Cannot find window." << std::endl;
}
else {
DWORD pId;
GetWindowThreadProcessId(hWnd, &pId);
HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pId);
if (hProc) {
char *newString = "newvalue";
size_t sz = strlen(newString) + 1;
LPVOID baseAddress = (LPVOID)0x009B03D0;
DWORD offset = 0xA7;
LPVOID ptrAddress = new char[sz];
SIZE_T bytes_read = 0, bytes_written=0;
if (ReadProcessMemory(hProc, baseAddress, ptrAddress, sz, &bytes_read) || GetLastError()== ERROR_PARTIAL_COPY) {
if (bytes_read == 0)
std::cerr << "Houston, we have a problem..." << std::endl;
if(!WriteProcessMemory(hProc, baseAddress, (LPCVOID)newString, sz, &bytes_written))
std::cerr << "Couldn't write process memory:" << GetLastError() << std::endl;
std::cout << "Done. " << bytes_read <<" bytes read and "<<bytes_written<<" bytes written"<< std::endl;
}
else {
std::cerr<< "Couldn't read process memory:" << GetLastError() << std::endl;
}
delete[] ptrAddress;
}
else {
std::cerr << "Couldn't open process " << pId << ": " << GetLastError() << std::endl;
}
}
std::getchar();
I'm running the following code with administrator privileges:
HANDLE hDevice = INVALID_HANDLE_VALUE; // handle to the drive to be examined
BOOL bResult = FALSE; // results flag
DWORD junk = 0; // discard results
hDevice = CreateFileW(L"\\\\.\\PhysicalDrive0", // drive to open
0, // no access to the drive
FILE_SHARE_READ | // share mode
FILE_SHARE_WRITE,
NULL, // default security attributes
OPEN_EXISTING, // disposition
0, // file attributes
NULL); // do not copy file attributes
if (hDevice == INVALID_HANDLE_VALUE) // cannot open the drive
{
std::cout << "invalid handle" << std::endl;
return -1;
}
std::cout << "handle " << hDevice << std::endl;
DRIVE_LAYOUT_INFORMATION_EX drv_layout_info_ex;
CREATE_DISK disk;
INT n;
ZeroMemory(&disk, sizeof(CREATE_DISK));
disk.PartitionStyle = PARTITION_STYLE_MBR;
disk.Mbr.Signature = 0x7B060725;
bResult = ::DeviceIoControl(hDevice, IOCTL_DISK_CREATE_DISK, &disk,
sizeof(CREATE_DISK), NULL,
0, &junk, NULL);
if (!bResult)
{
std::cout << "IOCTL_DISK_CREATE_DISK failed due to " << GetLastError() << std::endl;
return FALSE;
}
I get the output:
handle 00000048
IOCTL_DISK_CREATE_DISK failed due to 5
Which is access denied. What is the problem?