Skip to content

Instantly share code, notes, and snippets.

@nmulasmajic
Created July 20, 2017 23:07
Show Gist options
  • Save nmulasmajic/f51f98dc2f00564c63f5b7f4266474d3 to your computer and use it in GitHub Desktop.
Save nmulasmajic/f51f98dc2f00564c63f5b7f4266474d3 to your computer and use it in GitHub Desktop.
/*
* Module Name:
* ReadProcessMemory.cpp
*
* Abstract:
* Reads a blob of memory from the specified process.
*
* Author:
* Nemanja (Nemi) Mulasmajic <[email protected]>
* http://triplefault.io
*/
#pragma warning(disable: 4710)
#pragma warning(push, 0)
#include <Windows.h>
#include <stdio.h>
#pragma warning(pop)
/*
* The entry point.
*/
int main(int argc, char** argv)
{
int status = -1;
PCHAR LocalBuffer = NULL;
HANDLE RemoteProcess = NULL;
// Check for the right number of parameters passed in to this application.
if (argc != 4)
{
printf( "usage: app.exe [PID] [Address] [Size]\n"
"\t-> \"%s\" 1337 0xDEADBEEF 100\n", argv[0]);
goto Cleanup;
}
// Convert the argument strings to numbers.
DWORD RemoteProcessId = strtoul(argv[1], NULL, 0);
ULONG_PTR RemoteAddress = (ULONG_PTR)strtoull(argv[2], NULL, 0);
DWORD BufferSize = strtoul(argv[3], NULL, 0);
// Try to open the remote process with the ability to read virtual memory.
RemoteProcess = OpenProcess(PROCESS_VM_READ, FALSE, RemoteProcessId);
if (!RemoteProcess)
{
fprintf(stderr, "[-] ERROR: Couldn't open process %lu. OpenProcess failed with error: %lu.\n", RemoteProcessId, GetLastError());
goto Cleanup;
}
// Create a place to store the bytes we're going to read from the target process.
LocalBuffer = (PCHAR)malloc(BufferSize);
if (!LocalBuffer)
{
fprintf(stderr, "[-] ERROR: Failed to allocate %lu bytes for memory read.\n", BufferSize);
goto Cleanup;
}
SIZE_T BytesRead = 0;
// Read the bytes from the remote process and store it in our local buffer.
if (!ReadProcessMemory(RemoteProcess, (PVOID)RemoteAddress, LocalBuffer, BufferSize, &BytesRead) || BytesRead != BufferSize)
{
fprintf(stderr, "[-] ERROR: Failed to read %lu bytes from 0x%p in process %lu. ReadProcessMemory failed error: %lu.\n", BufferSize, (PVOID)RemoteAddress, RemoteProcessId, GetLastError());
goto Cleanup;
}
printf("[+] Success: Read %lu bytes from 0x%p in process %lu.\n", BufferSize, (PVOID)RemoteAddress, RemoteProcessId);
status = 0;
Cleanup:
// Free allocated memory.
if (LocalBuffer)
{
free(LocalBuffer);
LocalBuffer = NULL;
}
// Close handle.
if (RemoteProcess)
{
CloseHandle(RemoteProcess);
RemoteProcess = NULL;
}
// Wait for [ENTER] key press to terminate the program.
getchar();
return status;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment