Having MFA on a server is a good thing. But it can be a real PITA when you are required to pull out your phone for every single connection to the server, especially if you are performing some kind of automated task. Fortunately, ssh provides a mechanism to allow you to use the proper authentication methods to access the server, and then send all subsequent connections through that initial master pipe.
In my ssh config file, I have the following lines:
# Allow connection multiplexing so that it doesn't have to re-negotiate credentials # for subsequent connections to the same server. It will keep the connection alive # for 30 minutes in the background after last use of the first session. ControlMaster auto ControlPath ~/.ssh/controlmasters/%r@%h:%p ControlPersist 1800
For this to work, you need to have a folder called “
controlmasters” in your .ssh folder, and set the permissions to
0700 (making sure no one else can access it).
This uses “opportunistic multiplexing”, meaning that if there is an existing control master socket file, then use it, else create a new one. Simply put, your first connection to the server becomes a master connection, and it will terminate after 30 minutes (1800 seconds) if no sessions exist. You can set
no to have it shut the connection down immediately when the master connection closes, or you can set it to
yes to never terminate until you tell it to.
So if you log in in the morning, and you want to authenticate correctly to your work ssh hop box, you could run the command:
ssh -MNTfn hopbox.work.com
This will set up the master connection, not execute a shell or a pseudoTTY, prompt you for the necessary credentials, then fork into the background. Now any subsequent ssh connections you open to hopbox will go through that connection, without needing additional authentication. Once you are done for the day, and want to be sure you have closed out the master channel, you can run the command:
ssh -O exit hopbox.work.com
This command will terminate all other sessions you have going through it, so be sure you don’t have anything going on in another window before you shut down the connection.
In the event you need to connect to the server and do not want to go through the existing tunnel for any reason, just add “
-S none” to your ssh command:
ssh -S none hopbox.work.com
Now you will be prompted for your MFA credentials as usual.