You can see the list of processes using network resources with "netstat -peanut" or "lsof -i". Output the full executable path for each process.
You can see the list of processes using network resources with "netstat -peanut" or "lsof -i". Output the full executable path for each process.
Yesterday's Linux DFIR command line trivia asked us to get a listing of the full pathnames of executables for processes that are currently using network sockets. "netstat" and "lsof" can give us a list of PIDs, and then we will need to convert that to executable paths.
Let's start with "netstat":
netstat -peanut | tail -n +3 | sed -r 's/.* ([0-9]*)\/.*/\1/' | sort -un
"-peanut" is a helpful mnemonic for all processes ("-a") using TCP ("-t") and UDP ("-u") sockets, giving process info ("-p") but not converting IP addresses and ports into names ("-n"). "-e" just gives more detailed info and also allows us to spell "peanut" with the options.
We need "tail -n +3" to skip the header lines in the output. And then some crazy "sed" to extract just the PIDs. A final "sort -un" to give us just the unique PIDs in numerically sorted order.
And then @polyna dropped in to remind me that Linux deprecated "netstat" a long time ago. Sigh. Here's the same thing using "ss" like we all should be (but which my fingers generally refuse to type the first time):
ss -natup | sed -r 's/.*pid=([0-9]*).*/\1/' | sort -un
At least there are no header lines to skip in the "ss" output, but it's still some nasty "sed" to extract the PIDs.
Which is why I generally prefer the "lsof" option:
"lsof -i -t"
Yep, that's it. "-i" means show me processes using "internet sockets" and "-t" is "terse mode" which just outputs the PIDs. Terse mode is designed to be used with "kill" but we want to do something else with the PID list:
lsof -i -t | xargs -I{} readlink /proc/{}/exe
I could also do this with a loop, but "xargs" gives us a quick way to call "readlink /proc/<pid>/exe" for each PID from "lsof". The "-I{}" lets us create a marker for where we want "xargs" to put the PID in each command.
Why is this useful at all? See if you can spot the suspicious process in the sorted list of executables:
# lsof -i -t | xargs -I{} readlink /proc/{}/exe | sort -u
/dev/shm/.rk/lsof (deleted)
/dev/shm/.rk/xterm (deleted)
/usr/lib/systemd/systemd
/usr/sbin/dnsmasq
/usr/sbin/NetworkManager
/usr/sbin/sshd