logo

drewdevault.com

[mirror] blog and personal website of Drew DeVault git clone https://hacktivis.me/git/mirror/drewdevault.com.git

Redirecitng-stderr-of-running-process.md (2017B)


  1. ---
  2. date: 2018-05-04
  3. layout: post
  4. title: Redirecting stderr of a running process
  5. tags: [hack]
  6. ---
  7. During the KDE sprint in Berlin, [Roman Gilg](http://www.subdiff.de/) leaned
  8. over to me and asked if I knew how to redirect the stderr of an already-running
  9. process to a file. I Googled it and found underwhelming answers using strace and
  10. trying to decipher the output by reading the write syscalls. Instead, I thought
  11. a gdb based approach would work better, and after putting the pieces together
  12. Roman insisted I wrote a blog post on the topic.
  13. gdb, the GNU debugger, has two important features that make this possible:
  14. - Attaching to running processes via `gdb -p`
  15. - Executing arbitrary code in the target process space
  16. With this it's actually quite straightforward. The process is the following:
  17. 1. Attach gdb to the running process
  18. 2. Run `compile code -- dup2(open("/tmp/log", 65), 2)`
  19. The magic 65 here is the value of `O_CREAT | O_WRONLY` on Linux, which is easily
  20. found with a little program like this:
  21. ```c
  22. #include <sys/stat.h>
  23. #include <fcntl.h>
  24. int main(int argc, char **argv) {
  25. printf("%d\n", O_CREAT | O_WRONLY);
  26. return 0;
  27. }
  28. ```
  29. 2 is always the file descriptor assigned to stderr. What happens here is:
  30. 1. Via [`open`](https://linux.die.net/man/3/open), the file you want to redirect
  31. to is created.
  32. 2. Via [`dup2`](https://linux.die.net/man/3/dup2), stderr is overwritten with
  33. this new file.
  34. The `compile code` gdb command will compile some arbitrary C code and run the
  35. result in the target process, presumably by mapping some executable RAM and
  36. loading it in, then jumping to the blob. Closing gdb (control+d) will continue
  37. the process, and it should start writing out to the file you created.
  38. There are lots of other cool (and hacky) things you can do with gdb. I once
  39. disconnected someone from an internet radio by attaching gdb to nginx and
  40. closing their file descriptor, for example. Thanks to Roman for giving me the
  41. chance to write an interesting blog post on the subject!