I’ve switched from screen to tmux recently but I got one problem: when I left a session on a remote server, then anyone who is able to gain access to my user account would be able to also gain access to any remote shells or root shells within the tmux session. Since tmux doesn’t provice a way to protect from this, I created my own solution.

A simple script finds all privileged sessions running in the currently attached tmux session and kills it. The script is being executed as a hook when I detach from the session. It also echos a message about the fact to the windows so that I know a couple of days later where my root shell went etc.

So, here’s the script:

#!/bin/sh

termsubsession() {
  local index=$1
  local pid=$2
  local what="$3"
  local sendkeys="$4"

  echo "$what in window#$index under parent $pid, sending $sendkeys"
  tmux send-keys -t $index $sendkeys
  tmux run-shell -t $index "echo $what killed by $0"
}

tmux list-panes -s -F '#{pane_pid} #{window_index}' | while read PID INDEX; do
    pstree -p -a $PID | while read LINE; do
    if echo "$LINE" | egrep -q " root "; then
      termsubsession $INDEX $PID "root shell" "C-d C-d C-d"
      break
    elif echo "$LINE" | egrep -q "note -i"; then
      termsubsession $INDEX $PID "note -i" "q q C-m"
      break
    elif echo "$LINE" | egrep -q " /usr/bin/ssh "; then
      termsubsession $INDEX $PID "remote shell" "C-d"
      break
    fi
  done
done

Add this line to your .tmux.conf:

set-hook -g client-detached 'run-shell ~/bin/terminate-privileged-sessions.sh'

Take care if you try to adopt the solution. For example, I had to send 3 times C-d to my root shell. I start it usually using su - and then execute bash as root. So, 2 x C-d should be sufficient. But it didn’t work, for whatever reason.

Also note, that I do not just kill the processes in question. For the remote session killing the ssh client might be sufficient, but in case of the root shell it leads to the tmux window being closed. I was unable to figure out why this happend so I finally resorted to using tmux send-keys.