Unfortunately, I don't believe this is possible as an unprivileged user. I've searched for this quite a bit myself.
For my purposes, I allowed my "tunnel" user sudo access to the lsof command. I'm tunneling a service on one network, through my client, to the server, to be accessed by anyone on the servers network. I don't allow this user to do anything else (hence the "sleep infinity" and I have other rules in place to disable TTY and such)
/etc/sudoers
tunnel ALL=NOPASSWD:/usr/bin/lsof *
Using this script reports the connected port in the client window
#!/bin/bash #ip and port used by client to connect to server ip=`echo $SSH_CLIENT | awk '{ print $1 }'` sport=`echo $SSH_CLIENT | awk '{ print $2 }'` search="$ip:$sport" echo "Connected through $search" #returns the PID of the SSH Session spid=`sudo lsof -i 4 -n -P | grep "$search" | grep "tunnel" | awk '{ print $2 }'` #uses the pid of SSH session to find the tunneled port port=`sudo lsof -i 4 -n -P | grep "$spid" | grep "*:" | awk '{ print $9}' | sed 's/[^0-9]*//g'` if [ -z "$port" ] then #port returned empty echo "Unable to open tunnel. Please try again." echo " session closing in $i seconds" sleep 10 else echo "You've been assigned port $port" sleep infinity fi
I then force this commend to run on login from the /etc/sshd_config file
Match User tunnel ForceCommand /home/tunnel/tunnel.sh
Currently I'm only expecting to search for one port. Modification would be needed to check for more than one. I've removed some potentially redundant error checking I had in my original script. Further modification may be needed if you want your user to have access to TTY.