Linux: SSH and Key-Based Authentication (2024)

This article on services fits into a larger series of Linux articles covering various sysadmin topics, including hardware identification and managing system processes. You can build a lab environment by following the information in theLinux: Companion Lab for Linux Skill Blocks Repositoryarticle. In this series, we also coveredhow to pick a distributionandinstallation platform, how the Linux kernelinteracts with hardwareand howLinux manages system services,storage,file permissions,system processes, anduser and group permissions.

The Secure Shell (SSH) is a critical remote administration tool for Linux systems and network devices. It’s also essential for macOS access and is often added to Windows computers (or used in conjunction with PowerShell). I’ll demonstrate concepts and configurations using OpenSSH.

SSH’s primary benefits include the following:

  • Remote access to a wide variety of platforms.
  • Remote command execution.
  • Default installation on most Linux distributions.
  • Strong authentication mechanisms.
  • Support for secure file transfers, such as SCP and SFTP.
  • Provides tunneling for other non-secure applications.
  • Enhances automation and scripting.

Learning to leverage SSH is an essential Linux sysadmin skill. This article covers basic SSH configurations, password-based authentication and general security settings. It also shows how to improve SSH functionality with key-based authentication for better remote administration and integration with automation tools.

SSH helps mitigate eavesdropping attacks by encrypting authentication and network traffic. It’s a critical means of protecting administrative connections to servers, routers, switches, IoT devices and even cloud connections.

This article provides commands for managing remote Linux systems. I suggest using a Linux lab environment when completing these exercises. Review Understand the Linux Command Line to work with these commands better.

Establish an SSH Connection Using a Password

You might already know the basic SSH syntax for connecting to remote machines. Use thessh command and target a particular hostname or IP address:

1

$ ssh server07


Enhance the command by including the username for the remote user account you want to authenticate. For example, to connect using remote user admin03, type:

1

$ ssh admin03@server07


SSH prompts you to enter the password of the user account hosted on the remote system. On most systems, the command prompt will change to show the hostname of the remote computer.

At this point, you can begin executing Linux commands and run any programs installed on the remote device, such as Vim, Apache, or MariaDB. Remember that you may need to usesudo to elevate your privileges on the remote system.

Once you complete your remote administration tasks, typeexitorlogout to disconnect the SSH session.

Common SSH Use Cases

There are plenty of examples for using remote SSH connections, including:

  • Run remote backups with Duplicity, Kopia, tar or other tools.
  • Compile or install applications using compilers or package managers.
  • Modify system and application configuration files for web and database services.
  • Restart services. (Remember, you’ll be disconnected if you restart network or firewall services.)

However, the above use cases only allow for manual remote administration, where the administrator connects to one system at a time and runs commands (or scripts). It also means passwords must be tracked and maintained, which could be challenging when dealing with multiple remote devices.

Modern SSH implementations offer a far more robust way of proving your identity called key-based authentication. Implementing key-based authentication initially simplifies authentication for remote administration, but it is especially critical for automation functions.

Key-based authentication allows automation tools to authenticate to remote systems without requiring an administrator to type a password (or store a password in a configuration file). I examine this idea in more detail below.

What Is Key-Based Authentication?

Key-based authentication is a major improvement in SSH authentication, and it replaces password authentication. It relies on asymmetric key cryptography. This method relies on two mathematically related keys. Each key plays a specific role. The keys are:

  • Public key: This key can be transferred to remote systems across the network. Any data encrypted with the public key can only be decrypted with the related private key.
  • Private key: This key remains securely stored on the local device and never traverses the network. Any data encrypted with the private key can only be decrypted with the public key.

You’ll generate a public-private key pair on the administration workstation (the administrator’s local computer), then copy the public key to one or more remote servers.

During the connection attempt, the remote server encrypts a message challenge using the admin workstation’s public key. This message can only be decrypted with the admin workstation’s private key. If the workstation decrypts the challenge and replies with the correct information, the remote server knows its identity is confirmed.

The asymmetric keys are much harder to guess or brute-force than standard passwords, making this approach far more secure and reliable than passwords that may be based on predictable words or phrases.

Configure Key-Based Authentication for SSH

Implementing key-based SSH authentication is straightforward. The general steps are generating a key pair, copying the public key to the remote device and testing the connection.

Here is an explanation of the steps:

  1. Generate the key pair using thessh-keygen command. It creates two hidden files in the current user’s home directory. The files are~/.ssh/id_rsa (private key) and~/.ssh/id_rsa.pub (public key). You’ll typically press Enter through the interactive prompts.
  2. Copy the public key to the remote SSH device using thessh-copy-id command with the specified user. You must enter your password during this step, but this is the last time you’ll do so. The utility also prompts you for a yes or no confirmation. The public key file will reside in the~/.ssh/authorized_users file on the remote host.
  3. Test the connection by typingssh admin03@server07 (substitute your own credentials and hostname). The remote system should not challenge you for a password. The authentication is silent.

You’ll establish authenticated remote connections using the key pair from this point forward.

The following list summarizes the commands:

1

2

3

$ sudo ssh-keygen

$ sudo ssh-copy-id admin03@server07

$ sudo ssh admin03@server07

Linux: SSH and Key-Based Authentication (1)

Figure 1: Use the ssh-keygen command to generate a public/private key pair.

When you generate the key pair, you’ll be offered the chance to add a passphrase. You can also specify encryption algorithms and key sizes at this time. Most administrators will press Enter through these prompts, bypassing additional passphrase access.

After you copy the client’s public key to the remote server, you’ll no longer be challenged for a password during the connection attempt. Type the regular SSH connection command and the authentication process silently succeeds.

Use Key-Based Authentication for General Administration

The initial benefit of key-based authentication is simplicity. You’ll no longer be challenged for difficult-to-remember passwords. Authentication happens silently. The process is quicker, and you can begin your admin tasks immediately.

This is especially handy when you use SSH to quickly run a single remote command without manual intervention, such as:

1

# ssh admin03@server07 'run-backup.sh'


There’s no question this quicker authentication is helpful, but the real benefit of key-based SSH authentication occurs when automation gets involved.

Use Key-Based Authentication with Automation

SSH connectivity continues to be relevant in modern DevOps and Infrastructure as Code (IaC) environments. Many configuration management utilities must connect to remote systems to inventory software, manage settings, or initiate software testing. These tools must still authenticate to the remote systems if they use SSH.

Early approaches paused the configuration management tasks until administrators manually entered passwords. Clearly, that method does not enhance automation. Other designs embedded passwords or other authentication information directly in management files, risking accidental exposure to anyone who could access the files (or instances of the files, such as those found in backups).

Modern configuration management tools that use SSH can take advantage of key-based authentication to establish remote connections for a completely zero-touch solution.

Here are just a few automated configuration management tools that can use SSH connectivity:

  • Ansible
  • Chef
  • Puppet

Implementing key-based authentication means remote connections can be defined within these configuration management tools, and they’ll run without pausing for a manually entered password. There is no need for user intervention, which is essential when configuration management tasks run in the middle of the night or during scale-up incidents.

Another benefit of using keys for authentication is avoiding the need to embed passwords in deployment and configuration files. This risky practice can easily expose passwords for admin accounts.

Use Key-Based Authentication with Multiple Remote Servers

What if the admin workstation actually needs to connect to multiple remote SSH servers. You could maintain separate key pairs for each, but this would be very tedious. With a few quick configuration file edits, you can use the same key pair to authenticate to multiple remote devices. This approach even supports different connection options for each target system.

The steps to configure the local system for key-based authentication to multiple target servers begin in the same way as above. However, do not generate new key pairs for each connection. Each time you run thessh-keygen command it overwrites the existing key pair. You’ll use the same public and private keys for all connections.

The first two steps in the process are:

  1. Generate a key pair on the local system using thessh-keygen command.
  2. Copy the new public key to each remote server using thessh-copy-id command.

The most significant configuration change when dealing with multi-server connections is editing the client’s user-specific local SSH configuration file. Create (or edit) the~/.ssh/config file. You have several choices, including:

  • Hostnames.
  • Client identity files for various private keys.
  • Alternate port numbers.

For example, you might set up the following configuration to connect to various remote systems using a single private key namedid_rsa:

1

2

3

4

5

6

7

8

9

Host server07

Hostname server07

User admin03

IdentityFile ~/.ssh/id_rsa

Host server09

Hostname server09

User admin03

IdentityFile ~/.ssh/id_rsa


Finally, test the key-based authentication connection to ensure it can reach the remote device and to ensure the correct settings.

Configure Additional SSH Security Settings

SSH includes various other options to enhance security and customize its use in your environment. The primary SSH server configuration file is usually stored at/etc/ssh/sshd_config. It contains many entries. Review the comments and best practices carefully.

Here are some standard security configurations you may consider implementing.

  • Set SSH to refuse password-based authentication: PasswordAuthentication no.
  • Set SSH to refuse direct root logins across the network: PermitRootLogin no.
  • Change the default SSH port from 22 to a non-standard port to control connectivity.
  • Set a banner warning message.
  • Configure idle times to reduce hung connections. (Be careful of this setting with configuration managers, as it may be difficult to anticipate how long they will need to be connected.)

It’s poor security practice to log on to a local or remote Linux system as the root (administrator) user. Most systems force you to log on as a regular user and then use the sudo (super user do) command to elevate your privileges. You might be prompted for your password when usingsudo.

The PermitRootLogin no configuration mentioned above is a great way of enforcing this. You’ll establish the connection by authenticating with a non-privileged user on the remote SSH target, then elevate your privileges usingsudo on that box. Combine this method with key-based authentication to manage SSH security better.

Linux: SSH and Key-Based Authentication (2)

Figure 2: Customize the SSH server configuration file to match your company’s security policy.

Configure the Firewall for SSH

Remember to update your firewall settings. If SSH was preinstalled and running with your Linux distribution, the firewall is probably already open for port 22. If you have to add it, don’t forget to update the firewall rules to permit remote connections.

If you will only manage the server from a single admin workstation or jump box, restrict inbound SSH connections to that device’s identity only. That prevents SSH connections from any other network node.

Linux: SSH and Key-Based Authentication (3)

Figure 3: Most distributions default to port 22 open.

Audit Log Files for SSH Connections

Audit log files regularly for remote SSH connections to identify any unauthorized connections or repeated failed connection attempts. These may indicate users or malicious actors attempting to access the remote server.

If you manage several remote Linux servers using SSH, consider centralizing your log files using rsyslog. Doing so makes reviewing SSH connections easier, helping you verify that only authorized connections occur.

Wrap Up

Linux and network administrators rely on SSH for secure, convenient access to remote systems. It’s an essential part of their toolboxes. Password-based authentication to a few remote devices is viable, but it’s not convenient when implementing automation with lots of target servers.

Integrating SSH into your larger CI/CD and orchestration pipelines provides a simple, secure solution for remote connectivity. SSH functions with Linux, macOS, Windows and many network devices (routers, switches, etc.), making it a standard administration utility.

Start today by auditing your current SSH communications, then implement key-based authentication and automate as many configurations as possible. You might just find your environment is more secure and easier to work with.

TRENDING STORIES

Damon M. Garn owns Cogspinner Coaction, LLC, an IT writing and editing company. He authors articles, tutorials, and labs for today’s top IT industry leaders. He regularly contributes to The New Stack, TechTarget, and CompTIA. Damon has 20 years of... Read more from Damon M. Garn
Linux: SSH and Key-Based Authentication (2024)

FAQs

How to configure SSH for key-based authentication in Linux? ›

Configure SSH Key-based Authentication in Linux
  1. Step 1: Generate SSH Key Pair in Local System. ...
  2. Step 2: Copy SSH Public Key to SSH Server (Remote System) ...
  3. Step 3: Disable SSH Password-based Authentication in Remote SSH Server. ...
  4. Step 4: Test SSH Key-based Authentication. ...
  5. Step 5: Adding New Client System's Keys to SSH Server.
Sep 7, 2023

Are SSH keys enough? ›

SSH supports two main methods of authentication: passwords and keys. Passwords are easy to use and remember, but they are also vulnerable to brute-force attacks, phishing, and human errors. Keys are more secure and efficient, but they require more setup and management.

How do I turn off key-based authentication in Linux? ›

Disable public key authentication in SSH
  1. Log into SSH.
  2. Edit the file with your favorite editor: /etc/ssh/sshd_config.
  3. Lookup the variable: PasswordAuthentication and change 'no' to 'yes'
  4. Save and close the file.
  5. Run this command: service sshd reload.

Is SSH key-based authentication better than password? ›

Why authenticate using SSH key instead of password? Undeniably, the main advantage of authentication using SSH public key over authentication using password would be security. No matter how long or complex a password is, it can never equate with the cryptographic strength that SSH public key offers.

How to authenticate via SSH key? ›

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

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 best practice for SSH keys? ›

It should never be shared or transmitted over insecure networks. Consider encrypting private keys with a passphrase for additional security. Rotate SSH keys. Just like passwords, SSH keys should be changed or rotated regularly to reduce the risk of a key being used maliciously if it's compromised and unnoticed.

What is the most secure SSH key algorithm? ›

We strongly recommend using only the ed25519 algorithm (an ECDSA variant). It is the most secure SSH key type widely available, and is very well supported in the majority of systems. If you are using an client or server without ed25519 support, you should consider upgrading where possible.

Is SSH obsolete? ›

In terms of encryption algorithms, SSH is not necessarily outdated compared to newer options available in the security industry. SSH, or Secure Shell, is a protocol used for securely accessing and managing network devices and servers. The robustness of SSH depends on the encryption algorithms it employs.

How to configure SSH in Linux? ›

Set up personal SSH keys on Linux
  1. Install OpenSSH on your device.
  2. Start the SSH Agent.
  3. Create an SSH key pair.
  4. Add your key to the SSH agent.
  5. Provide Bitbucket Cloud with your public key.
  6. Check that your SSH authentication works.

How to fix too many authentication failures? ›

3 Ways to Fix Too many Authentication Failures SSH Root? [SOLVED]
  1. What are “Too Many Authentication Failures”?
  2. 3 Ways to Fix Too Many Authentication Failures.
  3. Method 1: Use SSH Key with Command Line.
  4. Method 2: Use Unique SSH Key for Each Server (Recommended)
  5. Method 3: Increase MaxAuthTries in SSH.
  6. Wrapping Up.
May 2, 2024

How do I generate a SSH key in Linux? ›

To generate an SSH key on your Linux server, run the command ssh-keygen . The command can take flags if you would like to customize the type of key that is generated and the signing algorithms that are used to generate the key. This example generates a standard 2048-bit RSA key without a passphrase.

Which is better SSH key Ed or RSA? ›

ED25519 is generally more efficient than RSA in terms of key size, computation, and memory. The key size of ED25519 is only 256 bits, while the key size of RSA is typically at least 2048 bits. This means that ED25519 requires less memory and computation to generate and verify signatures or encrypt and decrypt messages.

Which version of SSH is most secure? ›

Cryptographic Algorithms:
  • SSH-1 supports weaker, less secure algorithms.
  • SSH-2 supports stronger algorithms such as AES, ECDSA, and Ed25519, providing better encryption and security.
Jul 12, 2024

Is passwordless SSH more secure? ›

SSH Passwordless Login FAQ

If you simply press Enter without typing a passphrase, the key will be created without one. While this allows for passwordless authentication, it is important to note that such a key is less secure because it can be used by anyone who obtains the private key.

How do you specify a key in SSH config? ›

To specify which private key should be used for connections to a particular remote host, use a text editor to create a ~/. ssh/config that includes the Host and IdentityFile keywords. Once you save the file, SSH will use the specified private key for future connections to that host.

How to setup a key pair in SSH? ›

The simplest way to generate a key pair is to run ssh-keygen without arguments. In this case, it will prompt for the file in which to store keys. Here's an example: klar (11:39) ~>ssh-keygen Generating public/private rsa key pair.

How to enable SSH password authentication in Linux? ›

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

Top Articles
SunnySky X2212 KV980 Brushless Motors - Multirotor Version No Accessory
Gerrit Cole vs. Tyler O'Neill: Head-to-Head Stats Comparison | Stathead.com
Wsbtv Fish And Game Report
Corgsky Puppies For Sale
Capital In The Caribbean Nyt
Luxiconic Nails
Meet Scores Online 2022
Buff Streams .Io
Cbs Week 10 Trade Value Chart
Indiana girl set for final surgery 5 years after suffering burns in kitchen accident
24/7 Walmarts Near Me
Yogabella Babysitter
An Honest Review of Accor Live Limitless (ALL) Loyalty Program
Endocriene systeemklieren
Itouch Spa Marana
The Courier from Waterloo, Iowa
Get Got Lyrics
Warren County Skyward
Hours For Autozone Near Me
5 takeaways from Baylor’s historic comeback win vs. UCF: Bears find new energy in Orlando
Monahan's By The Cove Charlestown Menu
Hca Florida Middleburg Emergency Reviews
25+ Twitter Header Templates & Design Tips - Venngage
Dell Optiplex 7010 Drivers Download and Update for Windows 10
Sams Gas Price Garland Tx
Aunt Nettes Menu
Tri State Pediatrics Chippewa Pa
Conner Westbury Funeral Home Griffin Ga Obituaries
Proctor Funeral Home Obituaries Beaumont Texas
Penn Foster 1098 T Form
Southland Goldendoodles
Acnh Picnic Table
Holt French 2 Answers
Oasis Buds Slime Rancher
Cbs Sportsline Fantasy Rankings
Issue November 5, 1949 - The Hockey News
Roe V. Wade: The Abortion Rights Controversy in American History?second Edition, Revised and Expanded (Landmark Law Cases and American Society) - Taylor, Bob: 9780700617548
Secondary Math 2 Module 3 Answers
Section 212 Metlife Stadium
Lake Erie Noaa Near Shore
Www.cvs/Otchs/Simply
Pensacola Tattoo Studio 2 Reviews
Pulp Fiction 123Movies
Doomz.io Unblocked Games 76
358 Edgewood Drive Denver Colorado Zillow
Destep: 10 tips voor de scherpste destep-analyse ooit!
1By1 Roof
8 Internet Celebrities who fell prey to Leaked Video Scandals
Toldeo Craigslist
Gemini Home Entertainment Wiki
FINAL FANTASY XI Online 20th Anniversary | Square Enix Blog
Carenow Urgent Care - Eastchase Fort Worth Photos
Latest Posts
Article information

Author: Sen. Ignacio Ratke

Last Updated:

Views: 5482

Rating: 4.6 / 5 (56 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Sen. Ignacio Ratke

Birthday: 1999-05-27

Address: Apt. 171 8116 Bailey Via, Roberthaven, GA 58289

Phone: +2585395768220

Job: Lead Liaison

Hobby: Lockpicking, LARPing, Lego building, Lapidary, Macrame, Book restoration, Bodybuilding

Introduction: My name is Sen. Ignacio Ratke, I am a adventurous, zealous, outstanding, agreeable, precious, excited, gifted person who loves writing and wants to share my knowledge and understanding with you.