Skip to content

Instantly share code, notes, and snippets.

@ally-petitt
Created March 24, 2024 05:13
Show Gist options
  • Select an option

  • Save ally-petitt/f34fa7eba70703f5d44491fc6338b309 to your computer and use it in GitHub Desktop.

Select an option

Save ally-petitt/f34fa7eba70703f5d44491fc6338b309 to your computer and use it in GitHub Desktop.
Ptrace-Read-Program-Memory
/////////////////////////////////////////
// Title: Read Memory
// Description: Use ptrace to read memory
// of an executable.
// Author: Ally Petitt
/////////////////////////////////////////
#include <sys/ptrace.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/wait.h>
int read_mem(pid_t child, uint size) {
short read_word;
for (uint i=1; i <= size; i++) {
read_word = ptrace(PTRACE_PEEKDATA, child, i, NULL);
printf("%#2hhx ", read_word);
if (i % 10 == 0 )
puts(""); // put newline
ptrace(PTRACE_CONT, child, NULL, NULL);
}
ptrace(PTRACE_KILL, child, 0, 0);
printf("\n%i Bytes Read\n", size);
}
int main(int argc, char **argv) {
struct stat file_stat;
off_t filename;
pid_t child;
if (argc != 3) {
printf("Usage: %s <file_to_read> <bytes_to_read>", argv[0]);
exit(1);
}
// Start running file
child = fork();
if (child == 0) {
ptrace(PTRACE_TRACEME, 0, NULL, NULL);
execl(argv[1], argv[1], NULL);
} else {
wait(NULL);
read_mem(child, (uint) atoi(argv[2]));
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment