How does moving a unix domain socket enable socat to monitor traffic

socatsocket

socat can be used to monitor traffic across a Unix domain socket:

sudo mv /path/to/sock /path/to/sock.original
sudo socat -t100 -x -v UNIX-LISTEN:/path/to/sock,mode=777,reuseaddr,fork UNIX-CONNECT:/path/to/sock.original

I don't quite understand how this mechanism works, hoping someone could explain it a little. In particular, how does moving the socket file work if a process is already listening on it? Also, after the move:
neither lsof /path/to/sock nor /path/to/sock.original return any results.

Best Answer

Those commands have to be run when the server you want to monitor is currently listening on /path/to/sock. Then, if you rename /path/to/sock, the server won't be affected.

The socat command inserts a man-in-the-middle. It listens on /path/to/socks and forwards all the traffic by the clients to /path/to/socks.original (and logs it in the process with -v).

That only works for stream types of sockets (use UNIX-RECVFROM/UNIX-RECV for datagram sockets) and only if the clients just to read/write/send/recv on those sockets, not sendmsg() with ancillary data and other fancy things.

lsof will only report the listening processes (socat and the server for the listening and accepted sockets). It's generally not possible to link a connected socket on the client to the path of the socket.

If you do that before starting the server, then that won't work as the server will try to listen on /path/to/socks and fail as socat is already listening on that. Or you need to tell the server to listen on /path/to/sock.original instead.

Related Question