How to use SSH with 2FA (2024)

If affected still, you may want to add the-oServerAliveInterval=10 option to ssh (for Linux or Mac,putty has keepalive settings but not for command line); or leave

For incoming connections, ssh or putty talks to the firewall, and onlythe firewall knows which internal machine the connection is sent to:currently enna.

When using Cygwin (its ssh and its X server), or maybe from MacOSX,you need the (unsafe) -Y option instead of -X: I guess needed wheneverxdpyinfo does not show the SECURITY extension.

Dire warnings (words of Jim Richardson):
Note that skeys are only for use of the person to whom the sheet wasallocated, and no forwardings or tunnels other than the above shouldbe used without prior arrangement with the School Computing Manager.

Note for Maths (129.78.68.*, e.g. Magma) users:
You do not need 2FA from such "trusted" hosts.

Rate limits

On occasions, while trying to log in, you may receive errors like
 Connection closed by remote host server unexpectedly closed network connection Connection refused
or our Web-OTP service may show "Too Many Requests".

When that happens, try again in a little while. Long story below.

That is our protection against password guessing attacks, in action:we have rate limiting on ssh connections. When that happens, try againin a little while; or maybe wait until the next wall-clock hour, thentry; maybe use "ssh-v..." (or "putty-v...")to see the "error" message; try soon after the restriction is lifted,before the "bad guys" use up all permitted tries.

For some background, see:
https://isc.sans.edu/diary/Guess+what+SSH+again/6214
https://isc.sans.edu/diary/Dealing+With+Unwanted+SSH+Bruteforcing/7855/
and example log lines from 2011:

 Aug 25 22:17:33 bari sskd: Failed for invalid user aaa Aug 25 22:17:48 bari sskd: Failed for invalid user aaron Aug 25 22:17:51 bari sskd: Failed for invalid user abacus Aug 25 22:17:56 bari sskd: Failed for invalid user abby
Our ssh service is handled by:
  • xinetd (on our front-end or firewall machine siv or talus).
    In the file /etc/xinetd.conf we use the setting "cps=315":
    • Limit of three connections per second. When exceeded, xinetd will turn the port off for 15 seconds.
      When the port is turned off, a connection attempt gets a "connection refused", which I observed is better at making attackers go away.
      No longer have my cpm and cph patches in xinetd, but have rate limiting in the sshind script as below.
  • xinetd runs our sshind script (the reverse-proxy process). In sshind we have two kinds of rate limits:
    • Limits for each connecting machine. We keep a list of connection attempts, and each machine is allowed
      • 1 attempt per second
      • 3 attempts per minute, and
      • 10 attempts per hour.
      This successfully prevents many attacks.
    • Limit of all (remaining) connections during each wall-clock time period, allowing
      • 2 connections per second
      • 50 connections per minute, and
      • 500 connections per hour.
      until the start of the next wall-clock period.
      This prevents many distributed attacks, going through lists of login names but each attempt from a wildly different source IP address.
  • sshind proxies the connection to sskd (on enna, our login server). sskd is an skey- or 2FA-aware version of sshd, and runs with default "MaxStartups10:30:100" setting:
    • sshd will refuse connection attempts with a probability of 30% if there are currently 10 unauthenticated connections. The probability increases linearly and all connection attempts are refused if the number of unauthenticated connections reaches 100.
  • Our 2FA implementation in sskd has a "maxbadtries" lockout:
    • after 5 failed attempts at 2FA authentication, no more tries are permitted for an hour (the lockout is cleared automatically after the hour).
The limits on connections count both successful and failed logins.

Our Web-OTP service also has limits: 2 per minute for each connectingmachine, and a limit of 2 per second or 20 per minute for allconnections.

We are pretty safe against any breakins with 2FA; in fact I have nevernoticed them trying 2FA at all, they just try single passwords. Manytry root only as the login name (and root does not have 2FA).

We limit connections to protect against attackers wasting resources,hoping to make the attacker "go away" and try another victim. Ourprotections have stopped many ssh password guessing runs/attacks,significantly lowering the CPU load on our machines.

Any limits (in xinetd, sshind or sskd) will affect legitimate users also:hopefully our rates and back-off times are not too annoying.

Use xpra

Usexprato

  • avoid errors like
     Unrecognized OpenGL version Could not initialize GLX X server does not support XInput 2 GLX 1.3 or later is required
  • speed up your access
  • maybe leave your windows in place, for next login
Xpra is independent of (so you would not need) VcXsrv or XQuartz.
Using xpra may speed things up on slow networks like access from "outside",
but may instead slow things down on fast networks like internal ones,
and may introduce its own oddities and bugs.

Instructions:

  • Set things up as per Recommendations.
  • Setup (once only)
    • Linux or Mac
      On your laptop, install xpra from www.xpra.org.
      Linux distributions may have xpra, e.g. on Ubuntu simply use command
       sudoaptinstallxpra

      In a terminal window on your laptop (Applications>Accessories>Terminal), type commands:

       ln -sf ssh-with-2fa ~/bin/xpraterm ln -sf ssh-with-2fa ~/bin/xprasess
    • Windows
      On your laptop, install xpra from www.xpra.org.
      In a command prompt window on your laptop (Start>Programs>Accessories>CommandPrompt) or (Start>Run>cmd), type commands, but replacing MATHSNAME with your login name on the Maths servers:
       echo $x=$0; $x=~s,[a-z-]*$,ssh-with-2fa,; $y=`type "$x"`; eval $y > bin\xpraterm-helper echo $x=$0; $x=~s,[a-z-]*$,ssh-with-2fa,; $y=`type "$x"`; eval $y > bin\xprasess-helper echo perl "%USERPROFILE%\bin\xpraterm-helper" MATHSNAME@enna > bin\xpraterm.bat echo perl "%USERPROFILE%\bin\xprasess-helper" MATHSNAME@enna > bin\xprasess.bat
      Put shortcuts on your Desktop, pointing to xpraterm and xprasess: right-click anywhere in the desktop background, choose New Shortcut, browse to C:\Users\username\bin\xpraterm (or ...\xprasess) and OK.
  • How to use (daily)

    Use xpraterm if you want a terminal, so you can mix "native" and enna windows e.g. for copy-paste; use xprasess if you want a "desktop" session (though it may be slower than xpraterm).

    • Linux or Mac : In a terminal window on your laptop (Applications>Accessories>Terminal) type either command:
       xpraterm MATHSNAME@enna xprasess MATHSNAME@enna
      where MATHSNAME is your login name on the Maths servers.
    • Windows : Click the xpraterm or xrpasess icon on your Desktop
    to log in to enna with 2FA and password (each time your laptop re-connects to the network).
    To log out and terminate xpraterm or xprasess, in some enna window type command
     xpra stop
Enjoy the magic of indirection and subterfuge, one on top of another!

Comments about xpra (and other ways to use), for completeness:

  • If outside, log in with skeys and with 12022 port forwarding, as done by the ssh-with-2fa script, and leave that terminal running.

    On your laptop, in a new terminal (or command prompt) window, use command:
    Some (Mac?) machines do not know about localhost, then use 127.0.0.1 instead of the name localhost.

     xpra start ssh/MATHSNAME@localhost:12022 --no-speaker --exit-with-children=yes --start-child=xterm
    where MATHSNAME is your login name on the Maths servers.
    If doing from inside, then instead you need
     xpra start ssh/MATHSNAME@enna --no-speaker --exit-with-children=yes --start-child=xterm

    This (in a little while, password-less if you had set up public keys as suggested) will show a new xterm window running on enna; use this new xterm to work in/from.

    When "done", in some enna window use command

     xpra stop
    or simply close the various windows, and your xpra session will close also.
  • (Session retention un-tested, use at your own risk.)

    If you wanted to keep your xpra session "alive", then when "done", do not close the various windows but press ctrl-C where you started xpra. This would leave the "session" running on enna. Later you could re-connect to the xpra session: if outside, log in with skeys and then (on your laptop, in a new terminal window) use

     xpra attach ssh/MATHSNAME@localhost:12022 --no-speaker
    Some (Mac?) machines do not know about localhost, then use 127.0.0.1 instead of the name localhost.

    or if inside, (in a terminal window on your laptop) use

     xpra attach ssh/MATHSNAME@enna --no-speaker
    and see all your previous windows, as you had left them.

    You may have several sessions. To choose, add the number e.g.

     xpra attach ssh/MATHSNAME@localhost:12022/7 --no-speaker xpra attach ssh/MATHSNAME@enna/7 --no-speaker
    The same syntax could be used with xpra start if you wanted to choose some as-yet-unused one.
    Though, I suggest you have just the one xpra session, to enna (not savona etc directly):
    • one session only (so you never need to specify session numbers), and
    • to enna, from where you can xfrom to anywhere you like.

  • To clear left-over sessions off enna, log in to enna and (on enna) use
     xpra list
    to show all session numbers, and for each use something like
     xpra stop 7
    Please do this on occasions, not to leave things running forever.

Further reading, random references

en.wikipedia.org/wiki/Perl#Availability
en.wikipedia.org/wiki/Comparison_of_SSH_clients
en.wikipedia.org/wiki/X_Windows#Implementations
https://www.perl.org/get.html
www.openbsd.org/cgi-bin/man.cgi?query=ssh
www.openbsd.org/cgi-bin/man.cgi?query=ssh_config
puttytray.goeswhere.com/
cygwin.com/
x.cygwin.com/
www.starnet.com/products/xwin32/
connectivity.opentext.com/products/exceed.aspx
en.wikipedia.org/wiki/Port_forwarding
help.ubuntu.com/community/SSH/OpenSSH/PortForwarding
expect.sourceforge.net/
www.ora.com/catalog/expect/
blog.ropnop.com/extracting-ssh-private-keys-from-windows-10-ssh-agent/
arstechnica.com/features/2018/09/macos-10-14-mojave-the-ars-technica-review/12/
discussions.apple.com/thread/251226509
www.unix-ninja.com/p/attacking_google_authenticator

Paul Szabopsz@maths.usyd.edu.au15 Mar 24

How to use SSH with 2FA (2024)

FAQs

Does SSH support 2FA? ›

Implementing two-factor authentication (2FA) using PAM (Pluggable Authentication Module) in SSH with Google Authenticator is a great way to enhance the security of your SSH server. Google Authenticator generates time-based one-time passwords (TOTPs) for an additional layer of security.

How to enable MFA on SSH? ›

Enabling two-factor authentication for SSH
  1. Step 1: Disable root logins for SSH. If you haven't done so already, you should disable root SSH logins on your server and create a normal user account. ...
  2. Step 2: Install an authenticator app on a mobile device. ...
  3. Step 3: Enable two-factor authentication on the server.

How to configure key-based authentication for SSH? ›

Configure key-based SSH authentication
  1. Log in to the server console as the bitnami user.
  2. Create a key pair, consisting of a public and private key, as shown below. ...
  3. Copy the private key file named id_rsa to a secure location.
Feb 6, 2023

Does SSH require authentication? ›

As the SSH protocol is widely used for communication in cloud services, network environments, file transfer tools, configuration management tools, and other computer-dependent services, most organizations use this type of key-based authentication to verify identities and protect those services from unintended use or ...

Does SSH support mutual authentication? ›

In other words, it is possible to mutually authenticate in SSH with either a public key or with a public key certificate. TLS: While TLS does not mutually authenticate both ends of a connection by default, it can be used for this purpose.

How do I authenticate via SSH? ›

The SSH public key authentication has four steps:
  1. Generate a private and public key, known as the key pair. ...
  2. Add the corresponding public key to the server.
  3. The server stores and marks the public key as approved.
  4. The server allows access to anyone who proves the ownership of the corresponding private key.
Aug 10, 2021

How to enable password authentication in SSH? ›

Configure password-based SSH authentication
  1. Log in to the server console as the bitnami user.
  2. Edit the /etc/ssh/sshd_config and modify or add the following line: PasswordAuthentication yes.
  3. Restart the SSH server for the new configuration to take effect: sudo /etc/init.d/ssh force-reload sudo /etc/init.d/ssh restart.
Oct 10, 2022

Will SFTP method work with 2 factor authentication? ›

SFTP and SCP already support multi-factor authentication (MFA) using passwords and public keys, but this enhancement allows adding an additional factor to the password portion. We do not support 2FA with public keys alone.

How to configure 2FA in Linux? ›

Step by step guide to enable Linux MFA / 2FA (Two/Multi Factor Authentication) using SSH
  1. Download Linux MFA / 2FA SSH Module. ...
  2. Install and Configure MO-SSH Module. ...
  3. Configure Linux MFA / 2FA (Two-Factor Authentication) ...
  4. Test your Linux MFA / 2FA Setup. ...
  5. Configure Your User Directory (Optional)

How do I automate SSH authentication? ›

There are few steps you have to follow in order to automate your SSH login.
  1. Create an SSH key without Passphrase.
  2. Copy SSH key to the target server.
  3. Verification of copied SSH key in the remote server.
  4. Create bash aliases to easily remember the server domains or use SSH Config.
Sep 17, 2020

What are the permissions for SSH key authentication? ›

ssh directory permissions should be 700 (drwx------). The public key (. pub file) should be 644 (-rw-r--r--). The private key (id_rsa) on the client host, and the authorized_keys file on the server, should be 600 (-rw-------).

What is the default authentication method for SSH? ›

Indeed, SSH public key authentication is the de facto standard for security. In fact, not using keys is bad practice in most situations. Because of this, the key generation and setup procedure is streamlined, and the default value of PubkeyAuthentication is yes.

How do I make sure SSH is enabled? ›

In Server Manager, on the navigation pane to the left, select Local Server. In the Properties window, locate Remote SSH Access. Select Disabled to enable the OpenSSH service.

What is the difference between SSH authentication and signing? ›

The difference between signing keys and authentication keys is that signing keys can be used to sign Git commits and authentication keys can be used to access repositories. If you add a key as only one type, then it can be used only for that purpose, but the same key may be added for both.

How to secure a SSH connection? ›

Here are some best practices to ensure your authentication bulwark is as strong as it can be:
  1. Require strong passwords. ...
  2. Enable two-factor authentication. ...
  3. Regularly update passwords. ...
  4. Implement account lockouts. ...
  5. Educate users. ...
  6. Use SSH keys.

Does SSH support password authentication? ›

In password-based authentication, after establishing secure connection with remote servers, SSH users usually pass on their usernames and passwords to remote servers for client authentication. These credentials are shared through the secure tunnel established by symmetric encryption.

Does Keycloak support 2FA? ›

Two-factor authentication (2FA) can be enabled in Keycloak using either Google Authenticator or the One-Time Password(OTP) tool FreeOTP. For more background on OTPs, see Keycloak's documentation on OTP.

Can I use VoIP for 2FA? ›

Using VoIP numbers with 2FA

One of the limitations of using VoIP numbers for 2FA is that they might not always be recognized or accepted by all platforms or services.

References

Top Articles
Latest Posts
Recommended Articles
Article information

Author: Sen. Emmett Berge

Last Updated:

Views: 5900

Rating: 5 / 5 (80 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Sen. Emmett Berge

Birthday: 1993-06-17

Address: 787 Elvis Divide, Port Brice, OH 24507-6802

Phone: +9779049645255

Job: Senior Healthcare Specialist

Hobby: Cycling, Model building, Kitesurfing, Origami, Lapidary, Dance, Basketball

Introduction: My name is Sen. Emmett Berge, I am a funny, vast, charming, courageous, enthusiastic, jolly, famous person who loves writing and wants to share my knowledge and understanding with you.