How can a SSH host process detect which ports have been forwarded by the client (-R not -L)

(I can't decide between posting this here or on SuperUser but since this is for a sysadmin purpose, this seems like a better fit)

I have a situation where SSH clients will request a port forward using the -R option of SSH. At connection time, I want to be able to log which ports they forwarded.

I plan to do this by forcing a particular command to run (command=my-command in the authorized_keys file, that is) which will do this logging and then run the original command (login or user specified).

The only way I've found to do this so far requires running sudo and feels pretty hacky:

sudo lsof [email protected] -Fn -p12345 | grep "^n" | grep -v '\->' | awk -F: '{print $NF}' | sort | uniq* where 12345 is the process ID of the sshd that is handling this connection (i.e. the parent process of whatever script I run to check it.

Is there anything more elegant (a la the SSH_* environment variables that get set for other connection information) available to me?

* For the curious, the first part of the command gets all network ports bound to local interface ([email protected]) and (-a) belonging to process 12345 (-p12345) and formats it for machine readability (-Fn). The -P and -n flags makes it give the raw port numbers and network addresses. The second part (grep "^n") gives me back just the network information. The next part (grep -v '\->') eliminates established connections (thereby leaving "listening" ports). The next part (awk -F: '{print $NF}') uses awk to get the last field separated by ':', giving me the port (I don't use cut here because for an IPv6 connection, the field number might change). The last 2 parts just give me a unique list of ports. I put this explanation here because lsof is a fantastic command to know, and everyone should.


You can set the logging level of sshd to DEBUG1 and then grep the logs, you'll be looking for a line such as:

Dec 25 21:40:25 d34dh0r53 sshd[21963]: debug1: Local forwarding listening on ::1 port 8085.

Depending on which log file you use and the permissions you won't need to be root to read it.


ssh ~ keys ?

~# List forwarded connections.