Ptrace failing to attach

1.9k views Asked by At

I run my process as ./main &

It gives me an address that looks like this: [1] 4257

Then on a new terminal I do this: ./tracer 4257

This line of code is returning -1

ptrace(PTRACE_ATTACH, traced_process, NULL, NULL);

main.c

int main()
{
    int i;
    for(i = 0; i < 10; i++)
    {
        printf("Hello World\n");
        sleep(5);
    }

    return 0;
}

tracer.c

#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/user.h>   // For user_regs_struct

int main(int argc, char *argv[])
{  
    pid_t traced_process;
   struct user_regs_struct regs;

   if(argc != 2) 
   {
        printf("Usage: %s <pid to be traced>\n", argv[0], argv[1]);
        exit(1);
   }

   traced_process = atoi(argv[1]);

   long t = 0;
   t = ptrace(PTRACE_ATTACH, traced_process, NULL, NULL);

   if(t < 0)
    printf("-1\n");

   wait(NULL);

   ptrace(PTRACE_GETREGS, traced_process, NULL, &regs);
   long ins = ptrace(PTRACE_PEEKTEXT, traced_process, regs.eip, NULL);

   if(ins < 0)
    printf("-1\n");

   printf("EIP: %lx Instruction executed: %lx\n", regs.eip, ins);

   ptrace(PTRACE_DETACH, traced_process, NULL, NULL);

   return 0;
}

How do I fix this problem?

1

There are 1 answers

3
viraptor On BEST ANSWER

Ubuntu restricts the ability of other programs to attach via ptrace if there's no direct parent-child process relation (or you're not root).

Have a look at https://wiki.ubuntu.com/Security/Features#ptrace

Basically you need to allow tracing, or disable the protection system-wide by doing echo 0 > /proc/sys/kernel/yama/ptrace_scope