Search code examples
c++linuxttypts

Snooping on pseudo terminal


I want to write a program that can capture the input/output of a pseudo terminal without it affecting the original terminal. It can be likened to pointing script to a /dev/pts/<n>.

Use Case: A user ssh's into my machine and runs an interactive tool. With audit, I can see commands running but I need to see the output also. I can listen in on /dev/pts/<n> but then the original logged in user does not get the output.

I want to write my own program to handle this case. Is this problem actually solvable and if so, where should I be looking to find a solution?


Solution

  • That's solvable by using ptrace(2) on the ssh server process which handles to master end of the pseudo-terminal (which is usually the parent process of the shell running in the terminal).

    You can start with strace which is itself using ptrace(2), e.g.

    strace -p <pid> -e trace=read,write \
      -e read=<fds opened to /dev/ptmx> \
      -e write=<fds opened to /dev/ptmx>
    

    This will show you everything that's read or written to that pseudo-terminal. You can get the "fds opened to /dev/ptmx" from ls -l /proc/<pid>/fd.

    You can then look at what strace is doing -- e.g. by stracing strace itself with

    strace -e trace=ptrace,process_vm_readv strace ...
    

    and by studying its source code.

    You can of course modify the ssh server itself to log all that info, or just tweak its config options (e.g. LogLevel -- which can be modified on a per-user or connecting host basis).