Blog | G5 Cyber Security

GDB Attach After Privilege Drop

TL;DR

Attaching GDB to a process after it has dropped privileges requires careful setup. This guide explains how to do this, focusing on using a shared memory region for communication and setting up the correct permissions.

Steps

  1. Shared Memory Setup in the Target Process (Before Privilege Drop)
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h&gt>

int main() {
  const char *shmem_name = "/tmp/my_shared_memory";
  size_t shmem_size = 4096; // Example size
  int fd = shm_open(shmem_name, O_CREAT | O_RDWR, 0666);
  if (fd == -1) { perror("shm_open failed"); return 1; }
  ftruncate(fd, shmem_size); // Set size
  void *shmem = mmap(NULL, shmem_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  if (shmem == MAP_FAILED) { perror("mmap failed"); return 1; }
  *((int *)shmem) = 0x42424242; // Initial signal
  printf("Shared memory created at %pn", shmem);
  // ... rest of your program, including privilege drop ...
}
  • Privilege Drop
  • Perform the privilege drop using methods like setuid(), seteuid(), or by switching to a less privileged user. Ensure this happens *after* setting up the shared memory.

  • GDB Script Setup (On the Debugging Machine)
  • # gdb script (wait_for_attach.gdb)
    set $shmem_name = "/tmp/my_shared_memory"
    set $shmem_size = 4096
    
    while true {
      file /proc/[pid]/mem # Replace [pid] with the target process's PID
      p *((int *)$shmem_name)
      if ($result == 0x42424242) {
        break
      }
      sleep 1
    }
    attach [pid]
    
  • Attach with GDB
  • gdb -x wait_for_attach.gdb [target_process]
  • Verify Attachment
  • Once attached, verify that you can inspect the process’s memory and state within GDB.

  • Cleanup (Important)
  • Important Considerations

    Exit mobile version