Files
chmod760-CopyReadProcessMemory/CopyRemote/CopyRemote.cpp
T
2025-11-03 11:41:44 +01:00

75 lines
2.5 KiB
C++

// CopyRemote.cpp : Este archivo contiene la función "main". La ejecución del programa comienza y termina ahí.
//
#include <windows.h>
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;
int main() {
try {
// String a copiar
std::wstring AString = L"Hello, World";
SIZE_T AStringSize = AString.length() * sizeof(wchar_t);
void* pDummyBuffer = nullptr;
void* pNewBuffer = nullptr;
// Reservamos un buffer "dummy"
pDummyBuffer = malloc(UCHAR_MAX);
if (!pDummyBuffer)
throw std::runtime_error("GetMem failed");
try {
//
// Example 1: ReadProcessMemory
//
// Reservar memoria en el proceso actual con VirtualAlloc
pNewBuffer = VirtualAlloc(nullptr, AStringSize, MEM_COMMIT, PAGE_READWRITE);
std::wcout << L"Puntero en : " << pNewBuffer;
if (!pNewBuffer)
throw std::runtime_error("VirtualAlloc failed, le:" + std::to_string(GetLastError()));
// Copiar el buffer usando una API no relacionada (ReadProcessMemory)
SIZE_T* pDestOffset = nullptr;
char c;
cout << "Introduce un caracter: ";
cin >> c;
for (SIZE_T I = 0; I < AStringSize; ++I) {
pDestOffset = (SIZE_T*)((BYTE*)pNewBuffer + I);
// Esta llamada en realidad no copia correctamente, pero se deja igual que en Delphi
ReadProcessMemory(
GetCurrentProcess(), // handle del proceso
pNewBuffer, // dirección origen (??)
pDummyBuffer, // destino temporal
*((BYTE*)AString.data() + I), // tamaño (??)
(SIZE_T*)pDestOffset // bytes leídos
);
}
// Mostrar el resultado
std::wcout << L"Indirectly Copied String (ReadProcessMemory): \""
<< (wchar_t*)pNewBuffer << L"\"" << std::endl;
}
catch (...) {
if (pDummyBuffer) free(pDummyBuffer);
throw;
}
if (pDummyBuffer) free(pDummyBuffer);
if (pNewBuffer) VirtualFree(pNewBuffer, 0, MEM_RELEASE);
}
catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
return 0;
}