aboutsummaryrefslogtreecommitdiffstats
path: root/src/main.c
blob: 667ca4ca0f608dec50f79ec64c48c03070d4599c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <unistd.h>
#include "util.h"
#include "vm.h"

void hex2bytes(char *hex)
{
  size_t len = strlen(hex);
  char bytes[len + 1];

  for (size_t i = 0; i < len; ++i) {
    char hdig[3] = { hex[i*2], hex[i*2+1], '\0' };
    sscanf(hdig, "%hhx", &bytes[i]);
  }

  memcpy(hex, bytes, len);
  hex[len] = '\0';
}

int main(int argc, char *argv[])
{
  if (argc < 2) {
    ERROR("Usage: %s <tracee_pid>\n", argv[0]);
  }

  int pid;
  if ((pid = atoi(argv[1])) == 0) {
    ERROR("Invalid pid '%s'\n", argv[1]);
  }

  ptrace(PTRACE_ATTACH, pid, NULL, NULL);
  waitpid(pid, NULL, __WALL);
  LOG("Attached to process %d\n", pid);

  char *byte_seq = "DEADBEEF";
  size_t byte_seq_len = strlen(byte_seq);
  MemscanResult *head = memscan(pid, (uint8_t*)byte_seq, byte_seq_len);
  MemscanResult *cur = head;

  printf("\n\n\nMemory scan results:\n");
  printf("%-16s|%-16s|%-10s|%-s\n", "Address", "Base", "Offset", "Name");
  puts("--------------------------------------------------");
  while (cur) {
    printf("%-16p|%-16p|%#-10lx|%-s\n",
	   cur->mapping->begin + cur->offset,
	   cur->mapping->begin,
	   cur->offset,
	   cur->mapping->name);
    cur = cur->next;
  }

  printf("\n\n");

  char *buf = "CAFEBABE";
  size_t len = strlen(buf);
  cur = head;
  while (cur) {
    void *address = cur->mapping->begin + cur->offset;
    memwrite(pid, address, (uint8_t*)buf, len);
    cur = cur->next;
  }

  ptrace(PTRACE_DETACH, pid, NULL, NULL);
  LOG("Detached from process %d\n", pid);

  return 0;
}