Secure SSH in Red Hat Enterprise Linux

Red Hat Enterprise LinuxBeginner
Practice Now

Introduction

In this lab, you will gain hands-on experience with configuring and securing SSH connections, a fundamental skill for managing remote Linux systems. You will begin by learning how to access remote systems using SSH, understanding the client-server architecture and basic connection commands. This includes verifying SSH client installation, connecting to a remote host, handling host authenticity prompts, and logging in and out of remote systems.

Building on this foundation, you will then delve into more advanced topics such as generating and utilizing SSH key pairs for passwordless authentication, managing these keys effectively with ssh-agent, and troubleshooting common SSH connection issues. Finally, you will learn to customize SSH client configurations for improved efficiency and enhance the security of your OpenSSH server by disabling root login and password authentication, ensuring robust and secure remote access.

Access Remote Systems with SSH

In this step, you will learn how to access remote systems using SSH (Secure Shell). SSH is a cryptographic network protocol for operating network services securely over an unsecured network. It provides a secure channel over an unsecured network by using a client-server architecture, connecting an SSH client with an SSH server.

Note: In this lab environment, some security features like root login restrictions may already be configured for security purposes. This is normal and demonstrates best practices in action.

First, you will connect to the local system using SSH. This demonstrates the SSH client-server architecture even when connecting to the same machine. You will use the ssh command to connect to localhost.

The basic syntax for ssh is:
ssh [username]@[hostname_or_IP]

If you don't specify a username, SSH will attempt to log in with your current local username. In this case, your local username is labex.

Let's try to connect to localhost using your current username:

ssh localhost

When you connect for the first time, SSH will ask you to confirm the authenticity of the host. This is a security measure to prevent man-in-the-middle attacks. Type yes and press Enter.

The authenticity of host 'localhost (127.0.0.1)' can't be established.
ED25519 key fingerprint is SHA256:h5k1mmPFylpxUCsKx+Mf8rN4wOrk9TmyRfzTvGWRm7A.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'localhost' (ED25519) to the list of known hosts.
labex@localhost's password:

You will be prompted for the password of the labex user. Enter labex and press Enter.

labex@localhost's password:
Last login: Mon Jun  9 01:34:39 2025 from 47.251.66.143
[labex@host ~]$

You are now logged in via SSH to localhost. Notice that your prompt may show [labex@localhost ~]$, indicating you are connected via SSH.

To log out of the SSH session, use the exit command:

exit
logout
Connection to localhost closed.
[labex@host ~]$

Now, let's try connecting to localhost as the root user. Note that in this environment, root login may be disabled by default for security reasons.

ssh root@localhost

You will be prompted for the root password. However, you may encounter a "Permission denied" message if root login is disabled:

root@localhost's password:
Permission denied, please try again.
root@localhost's password:
Permission denied, please try again.
root@localhost's password:

If root login is disabled, this is expected behavior and demonstrates a security best practice. You can press Ctrl+C to cancel the connection attempt.

SSH can also be used to execute a single command on a remote system without opening an interactive shell. This is useful for quick checks or automation.

Let's run the hostname command on localhost as the labex user:

ssh labex@localhost hostname

You will be prompted for the labex user's password. Enter labex and press Enter.

labex@localhost's password:
6846375f1c0e35fea6cb03e6
[labex@host ~]$

The hostname command was executed via SSH, and its output was displayed on your local terminal. You were not dropped into an interactive shell.

Finally, let's explore how SSH manages known hosts. When you connect to a new SSH server, its public key fingerprint is added to your ~/.ssh/known_hosts file. This file helps your SSH client verify the identity of the server in future connections.

You can view the contents of your ~/.ssh/known_hosts file:

cat ~/.ssh/known_hosts
localhost ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHvl7dcZkvMNOr3cjKjlR2/JgFbGpURThT/bHnLZN6gG
localhost ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCynhy3601o9ZSGZoY0KB/QSonk5ykod2Tb7sCAqVn4ZgTCwd96BhPjJLPNQ6ldNASo1e7EzfT4BUjG5T0ZDRhgaI65qmDwITWipTWUfmYT5XoScyf6NDhcRxYiJwztFEkOvLcPhelS6UXj5Z7HdmYH4Nc5wiF00Wah3Jc0/2CfQsFZCXTn/7Kp8KKbBbPqPzr2R3WIULEacOxx9HKVv+2TvYg/OHZz40hTsr1c68DD7h5PMBNe21YB3HLRRk2LQEC7v7BFD+DCek9GNR66JBjbLDljtwWCaPCY0UntBjjvJ3W2LhX5RDZQHV/iaUSj2tEXnvPt9KSqGfBS91D12dBXyOmWVnTpvvI17BdDkEeefas2Uz4d7Bv/PDxZR6IKkaIGQ/ZnRhSEhBNvfqlBGqkOhRr6jQJK+rQMnsZCT6OEgW7osWzkw5Bs1wY/RNToeQqrRMclqffO9plFI688N2iT86+nxrvBVZg4yMMm2J1lleaBvinXCB8jE6lrtwoAdgk=
localhost ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBKYWY8Ty6TrbQS/0fUljBWuUpkyPCS/5P6ZwxhSYsqjRBIprMANI/JQotZqHYq2w3b2X/n8O+J3/WuIB6XMl1f4=

These entries confirm that your client has recorded multiple public keys for localhost (ED25519, RSA, and ECDSA). The SSH server may support multiple key types for compatibility. If any of these server keys ever change unexpectedly, SSH will warn you, which is a crucial security feature.

Generate and Use SSH Key Pairs for Passwordless Authentication

In this step, you will learn how to generate SSH key pairs and use them for passwordless authentication. SSH key-based authentication is a more secure and convenient alternative to password authentication. Instead of typing a password every time you connect, you use a pair of cryptographic keys: a private key (kept secret on your local machine) and a public key (placed on the remote server).

First, you need to generate an SSH key pair. You will use the ssh-keygen command for this purpose. By default, ssh-keygen creates an RSA key pair and saves the private key in ~/.ssh/id_rsa and the public key in ~/.ssh/id_rsa.pub.

Execute the ssh-keygen command:

ssh-keygen

You will be prompted for a few options:

Generating public/private rsa key pair.
Enter file in which to save the key (/home/labex/.ssh/id_rsa):

Press Enter to accept the default file path (/home/labex/.ssh/id_rsa).

Enter passphrase (empty for no passphrase):

For this lab, press Enter twice to leave the passphrase empty. While using a passphrase is recommended for real-world scenarios to add an extra layer of security, we will skip it here for simplicity and to demonstrate passwordless authentication directly.

Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/labex/.ssh/id_rsa
Your public key has been saved in /home/labex/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:QoV7pNBFu1kafGP3VJhpZuIdr1zc+qamJ1C2YAadgNY labex@6846375f1c0e35fea6cb03e6
The key's randomart image is:
+---[RSA 3072]----+
|     . *=o .   +.|
|    . =oE.o . O. |
|     o.++.=..*.+.|
|     .o .O+o+o. =|
|      ..So + o.+ |
|       .  . . +  |
|           .   . |
|            . o o|
|            .=.o |
+----[SHA256]-----+

Now, verify that the key files have been created in the ~/.ssh/ directory:

ls -l ~/.ssh/
total 16
-rw------- 1 labex labex 2622 Jun  9 01:37 id_rsa
-rw-r--r-- 1 labex labex  584 Jun  9 01:37 id_rsa.pub
-rw------- 1 labex labex  825 Jun  9 01:35 known_hosts
-rw-r--r-- 1 labex labex   91 Jun  9 01:35 known_hosts.old

You should see id_rsa (your private key) and id_rsa.pub (your public key). Note the permissions: id_rsa has rw------- (read/write only for the owner), which is crucial for security. You may also see known_hosts.old which is a backup of the previous known_hosts file.

Next, you need to copy your public key to enable passwordless authentication. The ssh-copy-id command is designed for this purpose. It appends your public key to the ~/.ssh/authorized_keys file, allowing you to log in without a password.

Execute the ssh-copy-id command, specifying the user and hostname:

ssh-copy-id labex@localhost

You will be prompted for the labex user's password. Enter labex and press Enter.

/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/labex/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
labex@localhost's password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'labex@localhost'"
and check to make sure that only the key(s) you wanted were added.

The command output confirms that one key was added. Now, try to log in to localhost as labex without providing a password:

ssh labex@localhost

If everything is configured correctly, you should be logged in via SSH without being prompted for a password.

Last login: Mon Jun  9 01:37:39 2025 from 47.251.66.143
[labex@host ~]$

You have successfully configured passwordless SSH authentication using key pairs!

To exit the remote session, type exit:

exit
exit
Connection to localhost closed.
[labex@host ~]$

Manage SSH Keys with ssh-agent

In this step, you will learn how to manage your SSH keys using ssh-agent. The ssh-agent is a program that runs in the background and holds your private keys in memory. This is particularly useful when your private keys are protected by a passphrase. Instead of typing the passphrase every time you use the key, you type it once when you add the key to the ssh-agent, and then the agent handles the authentication for you for the duration of your session.

Although you generated a key without a passphrase in the previous step, we will now create a new key with a passphrase to demonstrate the utility of ssh-agent.

First, generate a new SSH key pair with a passphrase. We will name this key id_rsa_passphrase to distinguish it from the default id_rsa key.

ssh-keygen -f ~/.ssh/id_rsa_passphrase

You will be prompted to enter a passphrase. For this lab, use mypassphrase as the passphrase.

Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase): mypassphrase
Enter same passphrase again: mypassphrase
Your identification has been saved in /home/labex/.ssh/id_rsa_passphrase
Your public key has been saved in /home/labex/.ssh/id_rsa_passphrase.pub
The key fingerprint is:
SHA256:BuSxVlJb1lsiUFi2I5DAvyL01fJ5d480LT86dgtcHEg labex@6846375f1c0e35fea6cb03e6
The key's randomart image is:
+---[RSA 3072]----+
|   ...=o+=*. E   |
|    .o.*.=..+ o  |
|     .=.o o. = . |
|  .  .+... .. . .|
| . . . +S.     + |
|  . o ..o . o * .|
|   . .   . . = * |
|             oooo|
|            ..+.o|
+----[SHA256]-----+

Note: If you accidentally press Enter without typing a passphrase, the key will be created without one. In that case, you can delete the files and run the command again, making sure to enter mypassphrase when prompted.

Now, let's copy this new public key to localhost so you can use it for authentication.

ssh-copy-id -i ~/.ssh/id_rsa_passphrase.pub labex@localhost

Since you already have passwordless authentication set up with your default key, the command may not prompt for a password and will use your existing authentication:

/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/labex/.ssh/id_rsa_passphrase.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'labex@localhost'"
and check to make sure that only the key(s) you wanted were added.

Now, try to connect to localhost using this new key. You will need to specify the private key file using the -i option.

ssh -i ~/.ssh/id_rsa_passphrase labex@localhost

If you set a passphrase for the key, you will be prompted for it. However, if you accidentally created the key without a passphrase (as shown in the example output), you will be logged in directly:

Last login: Mon Jun  9 01:39:25 2025 from 47.251.66.143
[labex@host ~]$

You are logged in. Now, exit the session:

exit
exit
Connection to localhost closed.
[labex@host ~]$

Note: If your key doesn't have a passphrase, you can still continue with the ssh-agent demonstration to understand how it works, even though it won't prompt for a passphrase in this case.

First, start the ssh-agent in your current shell session. The eval command is used to properly set the environment variables that ssh-agent outputs.

eval "$(ssh-agent)"
Agent pid 1024

The output will show the process ID (PID) of the ssh-agent.

Next, add your private key (id_rsa_passphrase) to the ssh-agent.

ssh-add ~/.ssh/id_rsa_passphrase

If your key has a passphrase, you will be prompted for it. If not, the key will be added directly:

Identity added: /home/labex/.ssh/id_rsa_passphrase (labex@6846375f1c0e35fea6cb03e6)

Now that the key is added to the ssh-agent, try connecting to localhost again using the same key.

ssh -i ~/.ssh/id_rsa_passphrase labex@localhost

You should be able to connect without being prompted for a passphrase (whether your key has one or not, since it's now managed by the agent):

Last login: Mon Jun  9 01:39:49 2025 from 127.0.0.1
[labex@host ~]$

You have successfully used ssh-agent to manage your SSH key.

Important Note: The ssh-agent environment variables are only available in the shell session where you started it. If you're in an SSH session, you need to exit back to your local shell to use ssh-add commands.

Exit the SSH session first:

exit
exit
Connection to localhost closed.
[labex@host ~]$

Now, to see the keys currently loaded in your ssh-agent, you can use ssh-add -l:

ssh-add -l

If the agent is running and has keys loaded, you'll see output like:

3072 SHA256:BuSxVlJb1lsiUFi2I5DAvyL01fJ5d480LT86dgtcHEg /home/labex/.ssh/id_rsa_passphrase (RSA)

However, if you see an error message like "Could not open a connection to your authentication agent", it means the agent environment variables are not set in your current session.

To remove all identities from the ssh-agent, use ssh-add -D:

ssh-add -D

If the agent is accessible, you'll see:

All identities removed.

However, if you see "Could not open a connection to your authentication agent", it means the agent environment is not available in your current session.

Now, if you try to connect again and your key has a passphrase, you will be prompted for it because the key has been removed from the agent:

ssh -i ~/.ssh/id_rsa_passphrase labex@localhost

If your key has a passphrase, you'll see:

Enter passphrase for key '/home/labex/.ssh/id_rsa_passphrase':

If your key doesn't have a passphrase, you'll still be able to connect directly. Press Ctrl+C to cancel the connection attempt if prompted for a passphrase.

Finally, to stop the ssh-agent process, you can use ssh-agent -k:

ssh-agent -k

If the SSH_AGENT_PID environment variable is not set, you may see:

SSH_AGENT_PID not set, cannot kill agent

This is normal if the agent was started in a different shell session or if the environment variables were not properly exported.

Troubleshoot SSH Connection Issues

In this step, you will learn how to troubleshoot common SSH connection issues. When SSH connections fail, it can be challenging to pinpoint the exact problem. The ssh command provides verbose output options that can help diagnose issues by showing detailed information about the connection process.

The ssh command offers three verbosity levels: -v, -vv, and -vvv. Each additional v increases the amount of debugging information displayed.

Let's start by attempting to connect to a non-existent port on localhost to demonstrate connection failure and see the debugging output.

First, try with -v (verbose) to connect to port 2222 (which should not be running):

ssh -v -p 2222 labex@localhost

You will see output similar to this, indicating that the connection is refused:

OpenSSH_8.7p1, OpenSSL 3.0.1 14 Dec 2021
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Reading configuration data /etc/ssh/ssh_config.d/01-training.conf
debug1: /etc/ssh/ssh_config.d/01-training.conf line 1: Applying options for *
debug1: Reading configuration data /etc/ssh/ssh_config.d/50-redhat.conf
debug1: /etc/ssh/ssh_config.d/50-redhat.conf line 3: Applying options for *
debug1: Connecting to localhost [127.0.0.1] port 2222.
ssh: connect to host localhost port 2222: Connection refused

Now, let's try with -vv (more verbose):

ssh -vv -p 2222 labex@localhost

The output will be more detailed, providing additional debugging messages:

OpenSSH_8.7p1, OpenSSL 3.0.1 14 Dec 2021
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Reading configuration data /etc/ssh/ssh_config.d/01-training.conf
debug1: /etc/ssh/ssh_config.d/01-training.conf line 1: Applying options for *
debug1: Reading configuration data /etc/ssh/ssh_config.d/50-redhat.conf
debug1: /etc/ssh/ssh_config.d/50-redhat.conf line 3: Applying options for *
debug2: resolving "localhost" port 2222
debug2: ssh_connect_direct: entering
debug1: Connecting to localhost [127.0.0.1] port 2222.
debug1: connect to address 127.0.0.1 port 2222: Connection refused
ssh: connect to host localhost port 2222: Connection refused

Finally, try with -vvv (most verbose):

ssh -vvv -p 2222 labex@localhost

This level provides the maximum amount of debugging information, which can be overwhelming but extremely useful for complex issues.

OpenSSH_8.7p1, OpenSSL 3.0.1 14 Dec 2021
debug3: ssh_connect_internal: entering
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Reading configuration data /etc/ssh/ssh_config.d/01-training.conf
debug1: /etc/ssh/ssh_config.d/01-training.conf line 1: Applying options for *
debug1: Reading configuration data /etc/ssh/ssh_config.d/50-redhat.conf
debug1: /etc/ssh/ssh_config.d/50-redhat.conf line 3: Applying options for *
debug2: resolving "localhost" port 2222
debug2: ssh_connect_direct: entering
debug1: Connecting to localhost [127.0.0.1] port 2222.
debug1: connect to address 127.0.0.1 port 2222: Connection refused
ssh: connect to host localhost port 2222: Connection refused

In this case, the error Connection refused clearly indicates that there is no SSH server running on port 2222.

Now, let's simulate a common issue: a changed host key. In the first step, you connected to localhost, and its public key was added to your ~/.ssh/known_hosts file. If the SSH server key were to change (e.g., due to a server rebuild or a malicious attack), your SSH client would detect this mismatch and refuse to connect.

To simulate this, we will intentionally modify the known_hosts entry for localhost to make it invalid.

First, open the ~/.ssh/known_hosts file using nano:

nano ~/.ssh/known_hosts

You will see multiple lines with different key types:

localhost ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHvl7dcZkvMNOr3cjKjlR2/JgFbGpURThT/bHnLZN6gG
localhost ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCynhy3601o9ZSGZoY0KB/QSonk5ykod2Tb7sCAqVn4ZgTCwd96BhPjJLPNQ6ldNASo1e7EzfT4BUjG5T0ZDRhgaI65qmDwITWipTWUfmYT5XoScyf6NDhcRxYiJwztFEkOvLcPhelS6UXj5Z7HdmYH4Nc5wiF00Wah3Jc0/2CfQsFZCXTn/7Kp8KKbBbPqPzr2R3WIULEacOxx9HKVv+2TvYg/OHZz40hTsr1c68DD7h5PMBNe21YB3HLRRk2LQEC7v7BFD+DCek9GNR66JBjbLDljtwWCaPCY0UntBjjvJ3W2LhX5RDZQHV/iaUSj2tEXnvPt9KSqGfBS91D12dBXyOmWVnTpvvI17BdDkEeefas2Uz4d7Bv/PDxZR6IKkaIGQ/ZnRhSEhBNvfqlBGqkOhRr6jQJK+rQMnsZCT6OEgW7osWzkw5Bs1wY/RNToeQqrRMclqffO9plFI688N2iT86+nxrvBVZg4yMMm2J1lleaBvinXCB8jE6lrtwoAdgk=
localhost ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBKYWY8Ty6TrbQS/0fUljBWuUpkyPCS/5P6ZwxhSYsqjRBIprMANI/JQotZqHYq2w3b2X/n8O+J3/WuIB6XMl1f4=

Choose one of the lines to modify. For this example, let's modify the ED25519 key (the first line). Modify a few characters in the long key string (e.g., change the last character from G to A). Be careful not to delete the entire line or other parts of the file.

For example, change:
...ZN6gG
to:
...ZN6gA

Save the file by pressing Ctrl+X, then Y to confirm saving, and Enter to confirm the filename.

Now, try to connect to localhost again:

ssh labex@localhost

You will receive a warning about a changed host key:

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the ED25519 key sent by the remote host is
SHA256:h5k1mmPFylpxUCsKx+Mf8rN4wOrk9TmyRfzTvGWRm7A.
Please contact your system administrator.
Add correct host key in /home/labex/.ssh/known_hosts to get rid of this message.
Offending key in /home/labex/.ssh/known_hosts:1
ED25519 host key for localhost has changed and you have requested strict checking.
Host key verification failed.

This is a critical security warning. If you encounter this in a real-world scenario, you should investigate why the host key changed. If it's a legitimate change (e.g., server reinstallation), you need to remove the old entry from known_hosts.

To fix this, you can either manually edit ~/.ssh/known_hosts and remove the offending line, or use ssh-keygen -R to remove the entry for localhost.

Let's use ssh-keygen -R to remove the incorrect entry:

ssh-keygen -R localhost
## Host localhost found: line 1
## Host localhost found: line 2
## Host localhost found: line 3
/home/labex/.ssh/known_hosts updated.
Original contents retained as /home/labex/.ssh/known_hosts.old

Now, try connecting to localhost again. You will be prompted to confirm the host's authenticity, just like the very first time you connected.

ssh labex@localhost
The authenticity of host 'localhost (127.0.0.1)' can't be established.
ED25519 key fingerprint is SHA256:h5k1mmPFylpxUCsKx+Mf8rN4wOrk9TmyRfzTvGWRm7A.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'localhost' (ED25519) to the list of known hosts.
Last login: Mon Jun  9 01:40:03 2025 from 127.0.0.1
[labex@host ~]$

You are now successfully connected again using key-based authentication.

Exit the session:

exit
exit
Connection to localhost closed.
[labex@host ~]$

Customize SSH Client Configurations

In this step, you will learn how to customize your SSH client configurations using the ~/.ssh/config file. This file allows you to define aliases and specific connection parameters for different remote hosts, simplifying your SSH commands and making them more consistent.

The ~/.ssh/config file is a powerful tool for managing your SSH connections. You can specify various options such as the username, the private key file to use, the port number, and even more advanced settings like proxy commands.

First, let's create or open the ~/.ssh/config file. If it doesn't exist, nano will create it.

nano ~/.ssh/config

Add the following configuration to the file. This configuration defines an alias localhost_labex for connecting to localhost as the labex user, and an alias localhost_root for connecting as the root user. It also explicitly specifies the IdentityFile for the labex user to use the id_rsa key generated in a previous step.

Host localhost_labex
    HostName localhost
    User labex
    IdentityFile ~/.ssh/id_rsa

Host localhost_root
    HostName localhost
    User root

Save the file by pressing Ctrl+X, then Y to confirm saving, and Enter to confirm the filename.

Now, let's try connecting to localhost using these new aliases.

Connect as labex using the localhost_labex alias:

ssh localhost_labex

Since you configured IdentityFile ~/.ssh/id_rsa and id_rsa does not have a passphrase, you should be logged in without being prompted for a password.

Last login: Mon Jun  9 01:54:16 2025 from 47.251.66.143
[labex@host ~]$

Exit the session:

exit
exit
Connection to localhost closed.
[labex@host ~]$

Now, connect as root using the localhost_root alias:

ssh localhost_root

You will be prompted for the root user's password. However, since root login is disabled in this environment, you will receive a "Permission denied" message:

root@localhost's password:
Permission denied, please try again.
root@localhost's password:

Press Ctrl+C to cancel the connection attempt:

^C

This demonstrates that the SSH configuration alias works, but the connection fails due to the security policy that disables root login.

As you can see, using the ~/.ssh/config file simplifies your SSH commands by pre-configuring common connection parameters.

Let's add another entry to demonstrate specifying a different port. While localhost uses the default SSH port (22), this example shows how you would configure it if it were different.

Open the ~/.ssh/config file again:

nano ~/.ssh/config

Add the following entry. This creates an alias localhost_port_example that explicitly sets the port to 2222. (Note: localhost does not actually listen on port 2222, so this connection will fail, but it demonstrates the configuration.)

Host localhost_labex
    HostName localhost
    User labex
    IdentityFile ~/.ssh/id_rsa

Host localhost_root
    HostName localhost
    User root

Host localhost_port_example
    HostName localhost
    Port 2222
    User labex

Save the file.

Now, try to connect using the localhost_port_example alias:

ssh localhost_port_example

This connection will fail because localhost is not listening on port 2222, but it demonstrates how to specify a custom port in your SSH config.

ssh: connect to host localhost port 2222: Cannot assign requested address

You can find some explanations for typical errors at this link:
            https://red.ht/support_rhel_ssh

You can view your current SSH configuration to see all the defined hosts:

cat ~/.ssh/config
Host localhost_labex
    HostName localhost
    User labex
    IdentityFile ~/.ssh/id_rsa

Host localhost_root
    HostName localhost
    User root

Host localhost_port_example
    HostName localhost
    Port 2222
    User labex

Finally, let's clean up the ~/.ssh/config file by removing the localhost_port_example entry.

Open the ~/.ssh/config file:

nano ~/.ssh/config

Delete the Host localhost_port_example block. The file should look like this:

Host localhost_labex
    HostName localhost
    User labex
    IdentityFile ~/.ssh/id_rsa

Host localhost_root
    HostName localhost
    User root

Save the file.

Understanding OpenSSH Server Security Configuration

In this step, you will learn about OpenSSH server security best practices by examining the current security configuration. You will understand how root login restrictions and password authentication settings work to protect your server from unauthorized access.

Note: In this lab environment, you will examine the current SSH security configuration and understand different security settings. This step focuses on understanding these security measures and learning about best practices for SSH server configuration.

Understanding Root Login Security

Allowing direct root login via SSH is generally discouraged because the root account has full administrative privileges. If an attacker gains access to the root account, they have complete control over your system. It's safer to log in as a regular user and then use sudo to perform administrative tasks.

Let's examine the current root login configuration and test its effectiveness.

First, log in via SSH as the labex user.

ssh labex@localhost

You should log in without a password if your SSH key setup from previous steps is correct.

Last login: Mon Jun  9 01:57:27 2025 from 47.251.66.143
[labex@host ~]$

Now, let's examine the SSH server configuration file to understand the current security settings:

sudo cat /etc/ssh/sshd_config | grep -E "^PermitRootLogin|^#PermitRootLogin"

This command will show you the current PermitRootLogin setting. You should see something like:

PermitRootLogin no

This setting means that direct root login via SSH is disabled, which is a security best practice.

Let's test if root login is actually blocked. First, exit the current SSH session:

exit
exit
Connection to localhost closed.
[labex@host ~]$

Now, attempt to log in as root to localhost:

ssh root@localhost

You should see a "Permission denied" message, indicating that direct root login is not allowed (this may already be configured in your environment).

root@localhost's password:
Permission denied, please try again.
root@localhost's password:
Permission denied, please try again.
root@localhost's password:

This confirms that root login is disabled in this environment, which is the desired security configuration. The "Permission denied" message demonstrates that the security measure is working effectively.

Understanding Password Authentication Security

Disabling password authentication forces users to rely on more secure methods like SSH key-based authentication. This significantly reduces the risk of brute-force attacks against your server.

Let's examine the current password authentication setting and understand how it works.

Log in via SSH as the labex user (using your SSH key):

ssh labex@localhost
Last login: Mon Jun  9 01:57:32 2025 from 127.0.0.1
[labex@host ~]$

First, let's check the current PasswordAuthentication setting:

sudo cat /etc/ssh/sshd_config | grep PasswordAuthentication
PasswordAuthentication yes
## PasswordAuthentication.  Depending on your PAM configuration,
## PAM authentication, then enable this but set PasswordAuthentication

As you can see, PasswordAuthentication yes is currently configured, which means password authentication is enabled. While this allows users to authenticate with passwords, it also presents a security risk as it makes the server vulnerable to brute-force password attacks.

The output shows:

  • PasswordAuthentication yes - This is the active setting that enables password authentication
  • The commented lines provide additional context about PAM configuration

This configuration means that users can authenticate using both passwords and SSH keys. For enhanced security, it's recommended to disable password authentication and rely solely on SSH key-based authentication.

Exit the current SSH session:

exit
exit
Connection to localhost closed.
[labex@host ~]$

Now, let's verify that SSH key-based authentication works properly while password authentication is disabled:

ssh labex@localhost

This should succeed without a password prompt, using your SSH key:

Last login: Mon Jun  9 02:00:22 2025 from 127.0.0.1
[labex@host ~]$

This demonstrates several important security concepts:

  1. Password authentication is enabled (PasswordAuthentication yes) - Users can log in with both passwords and SSH keys
  2. SSH key-based authentication works properly - More secure authentication method is available
  3. The server allows both authentication methods - While convenient, this may pose security risks from brute-force attacks
  4. Root login is disabled - Administrative access requires proper user escalation

Security Recommendation: For production environments, consider setting PasswordAuthentication no to enhance security by forcing users to use SSH key-based authentication only.

Exit the session:

exit
exit
Connection to localhost closed.
[labex@host ~]$

You have successfully examined and understood the OpenSSH server security configuration. The server currently has root login disabled (which follows security best practices) and password authentication enabled (which provides flexibility but may require additional security considerations for production environments). You've also verified that SSH key-based authentication works properly as a more secure authentication method.

Summary

In this lab, participants learned to access systems using SSH, starting with verifying the openssh-clients installation and connecting to localhost via SSH. They practiced authenticating with a password and understood the initial host authenticity check.

The lab further guided users through generating and utilizing SSH key pairs for passwordless authentication, managing these keys with ssh-agent, and troubleshooting common SSH connection issues. Finally, participants learned to customize SSH client configurations and secure the OpenSSH server by disabling root login and password authentication, enhancing their understanding of secure remote access practices.