Question

i want to catch information from user defined function using ptrace() calls.

but function address is not stable(because ASLR).

how can i get another program's function information like gdb programmatically?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <sys/ptrace.h>
#include <dlfcn.h>
#include <errno.h>

void error(char *msg)
{
    perror(msg);
    exit(-1);
}

int main(int argc, char **argv)
{
    long ret = 0;
    void *handle;
    pid_t pid = 0;
    struct user_regs_struct regs;
    int *hackme_addr = 0;

    pid = atoi(argv[1]);

    ret = ptrace(PTRACE_ATTACH, pid, NULL, NULL);
    if(ret<0)
    {
        error("ptrace() error");
    }

    ret = waitpid(pid, NULL, WUNTRACED);
    if(ret<0)
    {
        error("waitpid ()");
    }

    ret = ptrace(PTRACE_GETREGS, pid, NULL, &regs);
    if(ret<0)
    {
        error("GETREGS error");
    }

    printf("EIP : 0x%x\n", (int)regs.eip);

    ptrace(PTRACE_DETACH, pid, NULL, NULL);

    return 0;
}
Was it helpful?

Solution

ptrace is a bit ugly, but it can be useful.

Here's a ptrace example program; it's used to make I/O-related system calls pause. http://stromberg.dnsalias.org/~strombrg/slowdown/

You could of course also study gdb, but ISTR it's pretty huge.

You might also check out strace and ltrace, perhaps especially ltrace since it lists symbols.

HTH

OTHER TIPS

You probably want to call a function that resides in a specific executable (probably, a shared object). So, first, you will have to find the base address this executable is mapped on using

/proc/pid/maps

After that, you need to find the local offset of the function you are interested in, and you can do this in two ways:

  1. Understand the ELF file format (Linux native executable format), and searching the desired function using the mapped file (This requires some specialty)
  2. Using a ready to use elfparser (probably readelf tool) to get the function offset under the executable. Note that you will have to figure out the real local offset since this tool usually gives you the address as if the executable was mapped to a specific address
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top